relative_path
stringclasses 812
values | section
stringclasses 339
values | filename
stringlengths 2
61
| text
stringlengths 6
1.76M
|
---|---|---|---|
PyTorch/Classification/ConvNets/efficientnet/training/AMP | AMP | DGXA100_efficientnet-b0_AMP | python ./multiproc.py --nproc_per_node 8 ./launch.py --model efficientnet-b0 --precision AMP --mode convergence --platform DGXA100 /imagenet --workspace ${1:-./} --raport-file raport.json
|
TensorFlow2/Segmentation/Contrib/UNet3P/models | models | unet3plus | """
UNet3+ base model
"""
import tensorflow as tf
import tensorflow.keras as k
from .unet3plus_utils import conv_block
def unet3plus(encoder_layer, output_channels, filters):
""" UNet3+ base model """
""" Encoder """
e1 = encoder_layer[0]
e2 = encoder_layer[1]
e3 = encoder_layer[2]
e4 = encoder_layer[3]
e5 = encoder_layer[4]
""" Decoder """
cat_channels = filters[0]
cat_blocks = len(filters)
upsample_channels = cat_blocks * cat_channels
""" d4 """
e1_d4 = k.layers.MaxPool2D(pool_size=(8, 8))(e1) # 320*320*64 --> 40*40*64
e1_d4 = conv_block(e1_d4, cat_channels, n=1) # 320*320*64 --> 40*40*64
e2_d4 = k.layers.MaxPool2D(pool_size=(4, 4))(e2) # 160*160*128 --> 40*40*128
e2_d4 = conv_block(e2_d4, cat_channels, n=1) # 160*160*128 --> 40*40*64
e3_d4 = k.layers.MaxPool2D(pool_size=(2, 2))(e3) # 80*80*256 --> 40*40*256
e3_d4 = conv_block(e3_d4, cat_channels, n=1) # 80*80*256 --> 40*40*64
e4_d4 = conv_block(e4, cat_channels, n=1) # 40*40*512 --> 40*40*64
e5_d4 = k.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')(e5) # 80*80*256 --> 40*40*256
e5_d4 = conv_block(e5_d4, cat_channels, n=1) # 20*20*1024 --> 20*20*64
d4 = k.layers.concatenate([e1_d4, e2_d4, e3_d4, e4_d4, e5_d4])
d4 = conv_block(d4, upsample_channels, n=1) # 40*40*320 --> 40*40*320
""" d3 """
e1_d3 = k.layers.MaxPool2D(pool_size=(4, 4))(e1) # 320*320*64 --> 80*80*64
e1_d3 = conv_block(e1_d3, cat_channels, n=1) # 80*80*64 --> 80*80*64
e2_d3 = k.layers.MaxPool2D(pool_size=(2, 2))(e2) # 160*160*256 --> 80*80*256
e2_d3 = conv_block(e2_d3, cat_channels, n=1) # 80*80*256 --> 80*80*64
e3_d3 = conv_block(e3, cat_channels, n=1) # 80*80*512 --> 80*80*64
e4_d3 = k.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')(d4) # 40*40*320 --> 80*80*320
e4_d3 = conv_block(e4_d3, cat_channels, n=1) # 80*80*320 --> 80*80*64
e5_d3 = k.layers.UpSampling2D(size=(4, 4), interpolation='bilinear')(e5) # 20*20*320 --> 80*80*320
e5_d3 = conv_block(e5_d3, cat_channels, n=1) # 80*80*320 --> 80*80*64
d3 = k.layers.concatenate([e1_d3, e2_d3, e3_d3, e4_d3, e5_d3])
d3 = conv_block(d3, upsample_channels, n=1) # 80*80*320 --> 80*80*320
""" d2 """
e1_d2 = k.layers.MaxPool2D(pool_size=(2, 2))(e1) # 320*320*64 --> 160*160*64
e1_d2 = conv_block(e1_d2, cat_channels, n=1) # 160*160*64 --> 160*160*64
e2_d2 = conv_block(e2, cat_channels, n=1) # 160*160*256 --> 160*160*64
d3_d2 = k.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')(d3) # 80*80*320 --> 160*160*320
d3_d2 = conv_block(d3_d2, cat_channels, n=1) # 160*160*320 --> 160*160*64
d4_d2 = k.layers.UpSampling2D(size=(4, 4), interpolation='bilinear')(d4) # 40*40*320 --> 160*160*320
d4_d2 = conv_block(d4_d2, cat_channels, n=1) # 160*160*320 --> 160*160*64
e5_d2 = k.layers.UpSampling2D(size=(8, 8), interpolation='bilinear')(e5) # 20*20*320 --> 160*160*320
e5_d2 = conv_block(e5_d2, cat_channels, n=1) # 160*160*320 --> 160*160*64
d2 = k.layers.concatenate([e1_d2, e2_d2, d3_d2, d4_d2, e5_d2])
d2 = conv_block(d2, upsample_channels, n=1) # 160*160*320 --> 160*160*320
""" d1 """
e1_d1 = conv_block(e1, cat_channels, n=1) # 320*320*64 --> 320*320*64
d2_d1 = k.layers.UpSampling2D(size=(2, 2), interpolation='bilinear')(d2) # 160*160*320 --> 320*320*320
d2_d1 = conv_block(d2_d1, cat_channels, n=1) # 160*160*320 --> 160*160*64
d3_d1 = k.layers.UpSampling2D(size=(4, 4), interpolation='bilinear')(d3) # 80*80*320 --> 320*320*320
d3_d1 = conv_block(d3_d1, cat_channels, n=1) # 320*320*320 --> 320*320*64
d4_d1 = k.layers.UpSampling2D(size=(8, 8), interpolation='bilinear')(d4) # 40*40*320 --> 320*320*320
d4_d1 = conv_block(d4_d1, cat_channels, n=1) # 320*320*320 --> 320*320*64
e5_d1 = k.layers.UpSampling2D(size=(16, 16), interpolation='bilinear')(e5) # 20*20*320 --> 320*320*320
e5_d1 = conv_block(e5_d1, cat_channels, n=1) # 320*320*320 --> 320*320*64
d1 = k.layers.concatenate([e1_d1, d2_d1, d3_d1, d4_d1, e5_d1, ])
d1 = conv_block(d1, upsample_channels, n=1) # 320*320*320 --> 320*320*320
# last layer does not have batchnorm and relu
d = conv_block(d1, output_channels, n=1, is_bn=False, is_relu=False)
if output_channels == 1:
output = k.layers.Activation('sigmoid', dtype='float32')(d)
else:
output = k.layers.Activation('softmax', dtype='float32')(d)
return output, 'UNet_3Plus'
|
TensorFlow2/Recommendation/WideAndDeep/triton/runner | runner | core | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import dataclasses
import pathlib
from enum import Enum
from typing import Any, Dict, List
import yaml
class CustomDumper(yaml.Dumper):
"""
Custom YAML dumper to avoid craeting aliases
"""
def ignore_aliases(self, data: Dict) -> bool:
return True
class Paths:
"""
Paths mapping inside Triton Container
"""
MODEL_REPOSITORY_PATH = "/mnt/triton-models"
LIBRARIES_PATH = "/mnt/libs"
class Framework(Enum):
"""
Supported frameworks
"""
TensorFlow1 = "TensorFlow1"
TensorFlow2 = "TensorFlow2"
PyTorch = "PyTorch"
class Command:
"""Represents wrapper of raw string command"""
def __init__(self, data: str):
"""
Store command data
Args:
data: string with bash commands to execute
"""
self._data = data
def __str__(self) -> str:
"""
String object representation
Returns:
String
"""
return self._data
@dataclasses.dataclass
class Measurement:
offline_batch_sizes: List[int]
offline_concurrency: List[int]
online_batch_sizes: List[int]
online_concurrency: List[int]
min_shapes_batch: int
max_shapes_batch: int
opt_shapes_batch: int
class DataObject:
"""
Data object representation handling recursive transformation from object to dict
"""
READ_ONLY = set()
def to_dict(self) -> Dict:
"""
Represent object as dictionary
Returns:
Dict
"""
data = {}
filtered_data = {key: value for key, value in self.__dict__.items() if key not in self.READ_ONLY}
for key, value in filtered_data.items():
data[key] = self._convert_value(value)
return data
def _convert_value(self, value: Any) -> Any:
"""
Convert value based on its type
Args:
value: variable to convert
Returns:
Converted object
"""
if isinstance(value, DataObject):
value = value.to_dict()
elif isinstance(value, dict):
value = self._from_dict(value)
elif isinstance(value, list):
value = self._from_list(value)
elif isinstance(value, Enum):
value = value.value
elif isinstance(value, pathlib.Path):
value = value.as_posix()
return value
def _from_dict(self, values: Dict) -> Any:
"""
Convert dictionary values
Args:
values: dictionary with values
Returns:
Any
"""
data = {}
for key, value in values.items():
data[key] = self._convert_value(value)
return data
def _from_list(self, values: List) -> Any:
"""
Convert list of values
Args:
values: list with values
Returns:
Any
"""
items = []
for value in values:
item = self._convert_value(value)
items.append(item)
return items
AVAILABLE_FRAMEWORKS = [f.value for f in Framework]
class Batching(Enum):
DISABLED = "disabled"
STATIC = "static"
DYNAMIC = "dynamic"
|
PyTorch/Detection/Efficientdet/effdet/object_detection | object_detection | __init__ | # Copyright 2020 Google Research. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# Object detection data loaders and libraries are mostly based on RetinaNet:
# https://github.com/tensorflow/tpu/tree/master/models/official/retinanet
from .argmax_matcher import ArgMaxMatcher
from .box_coder import FasterRcnnBoxCoder
from .box_list import BoxList
from .matcher import Match
from .region_similarity_calculator import IouSimilarity
from .target_assigner import TargetAssigner
|
TensorFlow2/Recommendation/WideAndDeep/triton/runner | runner | downloader | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pathlib
import shutil
import urllib.request
from typing import Any, Callable
from zipfile import ZipFile
from retrying import retry
from tqdm.auto import tqdm
# method from PEP-366 to support relative import in executed modules
if __name__ == "__main__" and __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .logger import LOGGER
from .exceptions import RunnerException
def unzip(checkpoint_path: pathlib.Path, archive_path: pathlib.Path) -> None:
"""
Unzip acrhive to provided path
Args:
checkpoint_path: Path where archive has to be unpacked
archive_path: Path to archive Archive filename
Returns:
None
"""
LOGGER.info(f"Creating directory for checkpoint: {checkpoint_path.name}")
checkpoint_path.mkdir(parents=True, exist_ok=True)
LOGGER.info(f"Unpacking checkpoint files {checkpoint_path}")
with ZipFile(archive_path, "r") as zf:
zf.extractall(path=checkpoint_path)
LOGGER.info("done")
LOGGER.info(f"Removing zip file: {archive_path}")
archive_path.unlink()
LOGGER.info("done")
def download_progress(t: Any) -> Callable:
"""
Progress bar
Args:
t: progress
Returns:
Callable
"""
last_b = [0]
def update_to(b: int = 1, bsize: int = 1, tsize: int = None):
if tsize not in (None, -1):
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return update_to
@retry(stop_max_attempt_number=3)
def download(checkpoint_url: str, checkpoint_path: pathlib.Path) -> None:
"""
Download checkpoint from given url to provided path
Args:
checkpoint_url: Url from which checkpoint has to be downloaded
checkpoint_path: Path where checkpoint has to be stored
Returns:
None
"""
LOGGER.info(f"Downloading checkpoint from {checkpoint_url}")
with tqdm(unit="B") as t:
reporthook = download_progress(t)
result = urllib.request.urlretrieve(checkpoint_url, reporthook=reporthook)
filename = result[0]
LOGGER.info(f"Checkpoint saved in {filename}")
file_path = pathlib.Path(filename)
if not file_path.is_file() and not file_path.is_dir():
raise RunnerException(f"Checkpoint {filename} does not exist")
LOGGER.info(f"Moving checkpoint to {checkpoint_path.parent}")
shutil.move(file_path, checkpoint_path.parent / file_path.name)
LOGGER.info("done")
archive_path = checkpoint_path.parent / file_path.name
unzip(checkpoint_path, archive_path)
|
PyTorch/Forecasting/TFT/triton/runner | runner | utils | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pathlib
import shutil
import subprocess
from enum import Enum
from typing import Any, List, Optional
# method from PEP-366 to support relative import in executed modules
if __name__ == "__main__" and __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .core import Command
from .exceptions import RunnerException
from .logger import LOGGER
def format_env_key(s: str):
"""
Format environmental variable key
Args:
s: String to format
Returns:
Upper cased string
"""
return s.upper()
def format_env_value(value: Any) -> str:
"""
Format environment variable value
Args:
value: value to be formatted
Returns:
Formatted value as a string
"""
value = value if not isinstance(value, Enum) else value.value
value = value if type(value) not in [list, tuple] else ",".join(map(str, value))
value = str(value)
return value
def get_result_path(result_path: str) -> str:
"""
Map result path when different variants passed ex. with env variable in path
Args:
result_path: Path to result file
Returns:
str
"""
for env_var, val in os.environ.items():
result_path = result_path.replace(f"${{{env_var}}}", val)
if result_path.startswith("/"):
return result_path
if result_path.startswith("./"):
result_path = result_path[2:]
return result_path
def clean_directory(directory: pathlib.Path) -> None:
"""
Remove all files and directories from directory
Args:
directory: Path to directory which should be cleaned
Returns:
None
"""
LOGGER.debug(f"Cleaning {directory.as_posix()}")
if not directory.is_dir():
LOGGER.warning(f"{directory.name} is not a directory.")
return
for item in os.listdir(directory):
item_path = directory / item
if item_path.is_dir():
LOGGER.debug(f"Remove dir {item_path.as_posix()}")
shutil.rmtree(item_path.as_posix())
elif item_path.is_file():
LOGGER.debug(f"Remove file: {item_path.as_posix()}")
item_path.unlink()
else:
LOGGER.warning(f"Cannot remove item {item_path.name}. Not a file or directory.")
def exec_command(command: Command) -> None:
"""
Execute command
Args:
command: Command to run
"""
try:
process = subprocess.Popen(
[str(command)],
shell=True,
start_new_session=True,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
encoding="utf-8",
)
while True:
output = process.stdout.readline()
if output == "" and process.poll() is not None:
break
if output:
print(output.rstrip())
LOGGER.write(output)
result = process.poll()
if result != 0:
raise RunnerException(f"Command {command} failed with exit status: {result}")
except subprocess.CalledProcessError as e:
raise RunnerException(f"Running command {e.cmd} failed with exit status {e.returncode} : {e.output}")
|
PyTorch/DrugDiscovery/MoFlow/moflow | moflow | utils | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright 2020 Chengxi Zang
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import re
from typing import Dict, List, Optional, Tuple, Union
import numpy as np
from rdkit import Chem
import torch
from moflow.config import Config, ATOM_VALENCY, CODE_TO_BOND, DUMMY_CODE
def postprocess_predictions(x: Union[torch.Tensor, np.ndarray], adj: Union[torch.Tensor, np.ndarray], config: Config) -> Tuple[np.ndarray, np.ndarray]:
assert x.ndim == 3 and adj.ndim == 4, 'expected batched predictions'
n = config.dataset_config.max_num_atoms
adj = adj[:, :, :n, :n]
x = x[:, :n]
atoms = torch.argmax(x, dim=2)
atoms = _to_numpy_array(atoms)
adj = torch.argmax(adj, dim=1)
adj = _to_numpy_array(adj)
decoded = np.zeros_like(atoms)
for code, atomic_num in config.dataset_config.code_to_atomic.items():
decoded[atoms == code] = atomic_num
return decoded, adj
def convert_predictions_to_mols(adj: np.ndarray, x: np.ndarray, correct_validity: bool = False) -> List[Chem.Mol]:
molecules = [construct_mol(x_elem, adj_elem) for x_elem, adj_elem in zip(x, adj)]
if correct_validity:
molecules = [correct_mol(mol) for mol in molecules]
return molecules
def construct_mol(atoms: np.ndarray, adj: np.ndarray) -> Chem.Mol:
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
atoms_exist = (atoms != 0)
atoms = atoms[atoms_exist]
adj = adj[atoms_exist][:, atoms_exist]
mol = Chem.RWMol()
for atom in atoms:
mol.AddAtom(Chem.Atom(int(atom)))
for start, end in zip(*np.where(adj != DUMMY_CODE)):
if start > end:
mol.AddBond(int(start), int(end), CODE_TO_BOND[int(adj[start, end])])
# add formal charge to atom: e.g. [O+], [N+] [S+]
# not support [O-], [N-] [S-] [NH+] etc.
flag, atomid_valence = check_valency(mol)
if flag:
continue
else:
assert len(atomid_valence) == 2
idx = atomid_valence[0]
v = atomid_valence[1]
an = mol.GetAtomWithIdx(idx).GetAtomicNum()
if an in (7, 8, 16) and (v - ATOM_VALENCY[an]) == 1:
mol.GetAtomWithIdx(idx).SetFormalCharge(1)
return mol
def valid_mol(x: Optional[Chem.Mol]) -> Optional[Chem.Mol]:
if x is None:
# RDKit wasn't able to create the mol
return None
smi = Chem.MolToSmiles(x, isomericSmiles=True)
if len(smi) == 0 or '.' in smi:
# Mol is empty or fragmented
return None
reloaded = Chem.MolFromSmiles(smi)
# if smiles is invalid - it will be None, otherwise mol is valid
return reloaded
def check_valency(mol: Chem.Mol) -> Tuple[bool, List[int]]:
"""Checks that no atoms in the mol have exceeded their possible
valency. Returns True if no valency issues, False otherwise
plus information about problematic atom.
"""
try:
Chem.SanitizeMol(mol, sanitizeOps=Chem.SanitizeFlags.SANITIZE_PROPERTIES)
return True, None
except ValueError as e:
e = str(e)
p = e.find('#')
e_sub = e[p:]
atomid_valence = list(map(int, re.findall(r'\d+', e_sub)))
return False, atomid_valence
def correct_mol(mol: Chem.Mol) -> Chem.Mol:
flag, atomid_valence = check_valency(mol)
while not flag:
assert len(atomid_valence) == 2
idx = atomid_valence[0]
v = atomid_valence[1]
queue = []
for b in mol.GetAtomWithIdx(idx).GetBonds():
queue.append(
(b.GetIdx(), int(b.GetBondType()), b.GetBeginAtomIdx(), b.GetEndAtomIdx())
)
queue.sort(key=lambda tup: tup[1], reverse=True)
if len(queue) > 0:
start = queue[0][2]
end = queue[0][3]
t = queue[0][1] - 1
mol.RemoveBond(start, end)
if t >= 1:
mol.AddBond(start, end, CODE_TO_BOND[t])
flag, atomid_valence = check_valency(mol)
# if mol is fragmented, select the largest fragment
mols = Chem.GetMolFrags(mol, asMols=True)
mol = max(mols, key=lambda m: m.GetNumAtoms())
return mol
def predictions_to_smiles(adj: torch.Tensor, x: torch.Tensor, config: Config) -> List[str]:
x, adj = postprocess_predictions(x, adj, config=config)
valid = [Chem.MolToSmiles(construct_mol(x_elem, adj_elem), isomericSmiles=True)
for x_elem, adj_elem in zip(x, adj)]
return valid
def check_validity(molecules: List[Chem.Mol]) -> dict:
valid = [valid_mol(mol) for mol in molecules]
valid = [mol for mol in valid if mol is not None]
n_mols = len(molecules)
valid_ratio = len(valid) / n_mols
valid_smiles = [Chem.MolToSmiles(mol, isomericSmiles=False) for mol in valid]
unique_smiles = list(set(valid_smiles))
unique_ratio = 0.
if len(valid) > 0:
unique_ratio = len(unique_smiles) / len(valid)
valid_mols = [Chem.MolFromSmiles(s) for s in valid_smiles]
abs_unique_ratio = len(unique_smiles) / n_mols
results = dict()
results['valid_mols'] = valid_mols
results['valid_smiles'] = valid_smiles
results['valid_ratio'] = valid_ratio * 100
results['unique_ratio'] = unique_ratio * 100
results['abs_unique_ratio'] = abs_unique_ratio * 100
return results
def check_novelty(gen_smiles: List[str], train_smiles: List[str], n_generated_mols: int):
if len(gen_smiles) == 0:
novel_ratio = 0.
abs_novel_ratio = 0.
else:
duplicates = [1 for mol in gen_smiles if mol in train_smiles]
novel = len(gen_smiles) - sum(duplicates)
novel_ratio = novel * 100. / len(gen_smiles)
abs_novel_ratio = novel * 100. / n_generated_mols
return novel_ratio, abs_novel_ratio
def _to_numpy_array(a):
if isinstance(a, torch.Tensor):
a = a.cpu().detach().numpy()
elif isinstance(a, np.ndarray):
pass
else:
raise TypeError("a ({}) is not a torch.Tensor".format(type(a)))
return a
|
PyTorch/LanguageModeling/Transformer-XL/pytorch/utils | utils | distributed | # Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
from contextlib import contextmanager
import torch
def init_distributed(cuda):
"""
Initializes distributed backend.
:param cuda: (bool) if True initializes nccl backend, if False initializes
gloo backend
"""
world_size = int(os.environ.get('WORLD_SIZE', 1))
distributed = (world_size > 1)
if distributed:
backend = 'nccl' if cuda else 'gloo'
torch.distributed.init_process_group(backend=backend,
init_method='env://')
assert torch.distributed.is_initialized()
return distributed
def barrier():
"""
Call torch.distributed.barrier() if distritubed is in use, else calls
torch.cuda.synchronize() if CUDA is initialized.
"""
if torch.distributed.is_available() and torch.distributed.is_initialized():
torch.distributed.barrier()
elif torch.cuda.is_available() and torch.cuda.is_initialized():
torch.cuda.synchronize()
def get_rank():
"""
Gets distributed rank or returns zero if distributed is not initialized.
"""
if torch.distributed.is_available() and torch.distributed.is_initialized():
rank = torch.distributed.get_rank()
else:
rank = 0
return rank
def get_world_size():
"""
Gets total number of distributed workers or returns one if distributed is
not initialized.
"""
if torch.distributed.is_available() and torch.distributed.is_initialized():
world_size = torch.distributed.get_world_size()
else:
world_size = 1
return world_size
def all_reduce_item(value, op='sum'):
"""
All-reduces single scalar value if distributed is in use
"""
if torch.distributed.is_available() and torch.distributed.is_initialized():
if op == 'sum' or op == 'mean':
dop = torch.distributed.ReduceOp.SUM
elif op == 'min':
dop = torch.distributed.ReduceOp.MIN
elif op == 'max':
dop = torch.distributed.ReduceOp.MAX
elif op == 'product':
dop = torch.distributed.ReduceOp.PRODUCT
else:
raise RuntimeError('Unsupported reduce op')
backend = torch.distributed.get_backend()
if backend == torch.distributed.Backend.NCCL:
device = torch.device('cuda')
elif backend == torch.distributed.Backend.GLOO:
device = torch.device('cpu')
else:
raise RuntimeError('Unsupported distributed backend')
tensor = torch.tensor(value, device=device)
torch.distributed.all_reduce(tensor, dop)
if op == 'mean':
tensor /= get_world_size()
ret = tensor.item()
else:
ret = value
return ret
def all_gather_tensors(tensor, device):
tensor = tensor.to(device)
world_size = get_world_size()
if world_size == 1:
tensors = [tensor]
else:
tensors = [torch.empty_like(tensor) for _ in range(world_size)]
torch.distributed.all_gather(tensors, tensor)
return tensors
@contextmanager
def sync_workers():
"""
Yields distributed rank and synchronizes all workers on exit.
"""
rank = get_rank()
yield rank
barrier()
|
TensorFlow/Detection/SSD/models/research/object_detection/g3doc | g3doc | running_pets | # Quick Start: Distributed Training on the Oxford-IIIT Pets Dataset on Google Cloud
This page is a walkthrough for training an object detector using the Tensorflow
Object Detection API. In this tutorial, we'll be training on the Oxford-IIIT Pets
dataset to build a system to detect various breeds of cats and dogs. The output
of the detector will look like the following:
![](img/oxford_pet.png)
## Setting up a Project on Google Cloud
To accelerate the process, we'll run training and evaluation on [Google Cloud
ML Engine](https://cloud.google.com/ml-engine/) to leverage multiple GPUs. To
begin, you will have to set up Google Cloud via the following steps (if you have
already done this, feel free to skip to the next section):
1. [Create a GCP project](https://cloud.google.com/resource-manager/docs/creating-managing-projects).
2. [Install the Google Cloud SDK](https://cloud.google.com/sdk/downloads) on
your workstation or laptop.
This will provide the tools you need to upload files to Google Cloud Storage and
start ML training jobs.
3. [Enable the ML Engine
APIs](https://console.cloud.google.com/flows/enableapi?apiid=ml.googleapis.com,compute_component&_ga=1.73374291.1570145678.1496689256).
By default, a new GCP project does not enable APIs to start ML Engine training
jobs. Use the above link to explicitly enable them.
4. [Set up a Google Cloud Storage (GCS)
bucket](https://cloud.google.com/storage/docs/creating-buckets). ML Engine
training jobs can only access files on a Google Cloud Storage bucket. In this
tutorial, we'll be required to upload our dataset and configuration to GCS.
Please remember the name of your GCS bucket, as we will reference it multiple
times in this document. Substitute `${YOUR_GCS_BUCKET}` with the name of
your bucket in this document. For your convenience, you should define the
environment variable below:
``` bash
export YOUR_GCS_BUCKET=${YOUR_GCS_BUCKET}
```
It is also possible to run locally by following
[the running locally instructions](running_locally.md).
## Installing Tensorflow and the Tensorflow Object Detection API
Please run through the [installation instructions](installation.md) to install
Tensorflow and all it dependencies. Ensure the Protobuf libraries are
compiled and the library directories are added to `PYTHONPATH`.
## Getting the Oxford-IIIT Pets Dataset and Uploading it to Google Cloud Storage
In order to train a detector, we require a dataset of images, bounding boxes and
classifications. For this demo, we'll use the Oxford-IIIT Pets dataset. The raw
dataset for Oxford-IIIT Pets lives
[here](http://www.robots.ox.ac.uk/~vgg/data/pets/). You will need to download
both the image dataset [`images.tar.gz`](http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz)
and the groundtruth data [`annotations.tar.gz`](http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz)
to the `tensorflow/models/research/` directory and unzip them. This may take
some time.
``` bash
# From tensorflow/models/research/
wget http://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz
wget http://www.robots.ox.ac.uk/~vgg/data/pets/data/annotations.tar.gz
tar -xvf images.tar.gz
tar -xvf annotations.tar.gz
```
After downloading the tarballs, your `tensorflow/models/research/` directory
should appear as follows:
```lang-none
- images.tar.gz
- annotations.tar.gz
+ images/
+ annotations/
+ object_detection/
... other files and directories
```
The Tensorflow Object Detection API expects data to be in the TFRecord format,
so we'll now run the `create_pet_tf_record` script to convert from the raw
Oxford-IIIT Pet dataset into TFRecords. Run the following commands from the
`tensorflow/models/research/` directory:
``` bash
# From tensorflow/models/research/
python object_detection/dataset_tools/create_pet_tf_record.py \
--label_map_path=object_detection/data/pet_label_map.pbtxt \
--data_dir=`pwd` \
--output_dir=`pwd`
```
Note: It is normal to see some warnings when running this script. You may ignore
them.
Two 10-sharded TFRecord files named `pet_faces_train.record-*` and
`pet_faces_val.record-*` should be generated in the
`tensorflow/models/research/` directory.
Now that the data has been generated, we'll need to upload it to Google Cloud
Storage so the data can be accessed by ML Engine. Run the following command to
copy the files into your GCS bucket (substituting `${YOUR_GCS_BUCKET}`):
```bash
# From tensorflow/models/research/
gsutil cp pet_faces_train.record-* gs://${YOUR_GCS_BUCKET}/data/
gsutil cp pet_faces_val.record-* gs://${YOUR_GCS_BUCKET}/data/
gsutil cp object_detection/data/pet_label_map.pbtxt gs://${YOUR_GCS_BUCKET}/data/pet_label_map.pbtxt
```
Please remember the path where you upload the data to, as we will need this
information when configuring the pipeline in a following step.
## Downloading a COCO-pretrained Model for Transfer Learning
Training a state of the art object detector from scratch can take days, even
when using multiple GPUs! In order to speed up training, we'll take an object
detector trained on a different dataset (COCO), and reuse some of it's
parameters to initialize our new model.
Download our [COCO-pretrained Faster R-CNN with Resnet-101
model](http://storage.googleapis.com/download.tensorflow.org/models/object_detection/faster_rcnn_resnet101_coco_11_06_2017.tar.gz).
Unzip the contents of the folder and copy the `model.ckpt*` files into your GCS
Bucket.
``` bash
wget http://storage.googleapis.com/download.tensorflow.org/models/object_detection/faster_rcnn_resnet101_coco_11_06_2017.tar.gz
tar -xvf faster_rcnn_resnet101_coco_11_06_2017.tar.gz
gsutil cp faster_rcnn_resnet101_coco_11_06_2017/model.ckpt.* gs://${YOUR_GCS_BUCKET}/data/
```
Remember the path where you uploaded the model checkpoint to, as we will need it
in the following step.
## Configuring the Object Detection Pipeline
In the Tensorflow Object Detection API, the model parameters, training
parameters and eval parameters are all defined by a config file. More details
can be found [here](configuring_jobs.md). For this tutorial, we will use some
predefined templates provided with the source code. In the
`object_detection/samples/configs` folder, there are skeleton object_detection
configuration files. We will use `faster_rcnn_resnet101_pets.config` as a
starting point for configuring the pipeline. Open the file with your favourite
text editor.
We'll need to configure some paths in order for the template to work. Search the
file for instances of `PATH_TO_BE_CONFIGURED` and replace them with the
appropriate value (typically `gs://${YOUR_GCS_BUCKET}/data/`). Afterwards
upload your edited file onto GCS, making note of the path it was uploaded to
(we'll need it when starting the training/eval jobs).
``` bash
# From tensorflow/models/research/
# Edit the faster_rcnn_resnet101_pets.config template. Please note that there
# are multiple places where PATH_TO_BE_CONFIGURED needs to be set.
sed -i "s|PATH_TO_BE_CONFIGURED|"gs://${YOUR_GCS_BUCKET}"/data|g" \
object_detection/samples/configs/faster_rcnn_resnet101_pets.config
# Copy edited template to cloud.
gsutil cp object_detection/samples/configs/faster_rcnn_resnet101_pets.config \
gs://${YOUR_GCS_BUCKET}/data/faster_rcnn_resnet101_pets.config
```
## Checking Your Google Cloud Storage Bucket
At this point in the tutorial, you should have uploaded the training/validation
datasets (including label map), our COCO trained FasterRCNN finetune checkpoint and your job
configuration to your Google Cloud Storage Bucket. Your bucket should look like
the following:
```lang-none
+ ${YOUR_GCS_BUCKET}/
+ data/
- faster_rcnn_resnet101_pets.config
- model.ckpt.index
- model.ckpt.meta
- model.ckpt.data-00000-of-00001
- pet_label_map.pbtxt
- pet_faces_train.record-*
- pet_faces_val.record-*
```
You can inspect your bucket using the [Google Cloud Storage
browser](https://console.cloud.google.com/storage/browser).
## Starting Training and Evaluation Jobs on Google Cloud ML Engine
Before we can start a job on Google Cloud ML Engine, we must:
1. Package the Tensorflow Object Detection code.
2. Write a cluster configuration for our Google Cloud ML job.
To package the Tensorflow Object Detection code, run the following commands from
the `tensorflow/models/research/` directory:
```bash
# From tensorflow/models/research/
bash object_detection/dataset_tools/create_pycocotools_package.sh /tmp/pycocotools
python setup.py sdist
(cd slim && python setup.py sdist)
```
This will create python packages dist/object_detection-0.1.tar.gz,
slim/dist/slim-0.1.tar.gz, and /tmp/pycocotools/pycocotools-2.0.tar.gz.
For running the training Cloud ML job, we'll configure the cluster to use 5
training jobs and three parameters servers. The
configuration file can be found at `object_detection/samples/cloud/cloud.yml`.
Note: The code sample below is supported for use with 1.9 runtime version.
To start training and evaluation, execute the following command from the
`tensorflow/models/research/` directory:
```bash
# From tensorflow/models/research/
gcloud ml-engine jobs submit training `whoami`_object_detection_pets_`date +%m_%d_%Y_%H_%M_%S` \
--runtime-version 1.9 \
--job-dir=gs://${YOUR_GCS_BUCKET}/model_dir \
--packages dist/object_detection-0.1.tar.gz,slim/dist/slim-0.1.tar.gz,/tmp/pycocotools/pycocotools-2.0.tar.gz \
--module-name object_detection.model_main \
--region us-central1 \
--config object_detection/samples/cloud/cloud.yml \
-- \
--model_dir=gs://${YOUR_GCS_BUCKET}/model_dir \
--pipeline_config_path=gs://${YOUR_GCS_BUCKET}/data/faster_rcnn_resnet101_pets.config
```
Users can monitor and stop training and evaluation jobs on the [ML Engine
Dashboard](https://console.cloud.google.com/mlengine/jobs).
## Monitoring Progress with Tensorboard
You can monitor progress of the training and eval jobs by running Tensorboard on
your local machine:
```bash
# This command needs to be run once to allow your local machine to access your
# GCS bucket.
gcloud auth application-default login
tensorboard --logdir=gs://${YOUR_GCS_BUCKET}/model_dir
```
Once Tensorboard is running, navigate to `localhost:6006` from your favourite
web browser. You should see something similar to the following:
![](img/tensorboard.png)
Make sure your Tensorboard version is the same minor version as your Tensorflow (1.x)
You will also want to click on the images tab to see example detections made by
the model while it trains. After about an hour and a half of training, you can
expect to see something like this:
![](img/tensorboard2.png)
Note: It takes roughly 10 minutes for a job to get started on ML Engine, and
roughly an hour for the system to evaluate the validation dataset. It may take
some time to populate the dashboards. If you do not see any entries after half
an hour, check the logs from the [ML Engine
Dashboard](https://console.cloud.google.com/mlengine/jobs). Note that by default
the training jobs are configured to go for much longer than is necessary for
convergence. To save money, we recommend killing your jobs once you've seen
that they've converged.
## Exporting the Tensorflow Graph
After your model has been trained, you should export it to a Tensorflow graph
proto. First, you need to identify a candidate checkpoint to export. You can
search your bucket using the [Google Cloud Storage
Browser](https://console.cloud.google.com/storage/browser). The file should be
stored under `${YOUR_GCS_BUCKET}/model_dir`. The checkpoint will typically
consist of three files:
* `model.ckpt-${CHECKPOINT_NUMBER}.data-00000-of-00001`
* `model.ckpt-${CHECKPOINT_NUMBER}.index`
* `model.ckpt-${CHECKPOINT_NUMBER}.meta`
After you've identified a candidate checkpoint to export, run the following
command from `tensorflow/models/research/`:
```bash
# From tensorflow/models/research/
gsutil cp gs://${YOUR_GCS_BUCKET}/model_dir/model.ckpt-${CHECKPOINT_NUMBER}.* .
python object_detection/export_inference_graph.py \
--input_type image_tensor \
--pipeline_config_path object_detection/samples/configs/faster_rcnn_resnet101_pets.config \
--trained_checkpoint_prefix model.ckpt-${CHECKPOINT_NUMBER} \
--output_directory exported_graphs
```
Afterwards, you should see a directory named `exported_graphs` containing the
SavedModel and frozen graph.
## Configuring the Instance Segmentation Pipeline
Mask prediction can be turned on for an object detection config by adding
`predict_instance_masks: true` within the `MaskRCNNBoxPredictor`. Other
parameters such as mask size, number of convolutions in the mask layer, and the
convolution hyper parameters can be defined. We will use
`mask_rcnn_resnet101_pets.config` as a starting point for configuring the
instance segmentation pipeline. Everything above that was mentioned about object
detection holds true for instance segmentation. Instance segmentation consists
of an object detection model with an additional head that predicts the object
mask inside each predicted box once we remove the training and other details.
Please refer to the section on [Running an Instance Segmentation
Model](instance_segmentation.md) for instructions on how to configure a model
that predicts masks in addition to object bounding boxes.
## What's Next
Congratulations, you have now trained an object detector for various cats and
dogs! There different things you can do now:
1. [Test your exported model using the provided Jupyter notebook.](running_notebook.md)
2. [Experiment with different model configurations.](configuring_jobs.md)
3. Train an object detector using your own data.
|
PyTorch/Forecasting/TFT/triton | triton | run_inference_on_triton | #!/usr/bin/env python3
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
r"""
To infer the model deployed on Triton, you can use `run_inference_on_triton.py` script.
It sends a request with data obtained from pointed data loader and dumps received data into dump files.
Those files are stored in directory pointed by `--output-dir` argument.
Currently, the client communicates with the Triton server asynchronously using GRPC protocol.
Example call:
```shell script
python ./triton/run_inference_on_triton.py \
--server-url localhost:8001 \
--model-name ResNet50 \
--model-version 1 \
--dump-labels \
--output-dir /results/dump_triton
```
"""
import argparse
import functools
import logging
import queue
import threading
import time
import traceback
from pathlib import Path
from typing import Optional
from tqdm import tqdm
# pytype: disable=import-error
try:
from tritonclient import utils as client_utils # noqa: F401
from tritonclient.grpc import InferenceServerClient, InferInput, InferRequestedOutput
except ImportError:
from tritongrpcclient import InferenceServerClient, InferInput, InferRequestedOutput
# pytype: enable=import-error
# method from PEP-366 to support relative import in executed modules
if __package__ is None:
__package__ = Path(__file__).parent.name
from .deployment_toolkit.args import ArgParserGenerator
from .deployment_toolkit.core import DATALOADER_FN_NAME, load_from_file
from .deployment_toolkit.dump import JsonDumpWriter
LOGGER = logging.getLogger("run_inference_on_triton")
class SyncGRPCTritonRunner:
DEFAULT_MAX_RESP_WAIT_S = 120
def __init__(
self,
server_url: str,
model_name: str,
model_version: str,
*,
dataloader,
verbose=False,
resp_wait_s: Optional[float] = None,
):
self._server_url = server_url
self._model_name = model_name
self._model_version = model_version
self._dataloader = dataloader
self._verbose = verbose
self._response_wait_t = self.DEFAULT_MAX_RESP_WAIT_S if resp_wait_s is None else resp_wait_s
def __iter__(self):
client = InferenceServerClient(self._server_url, verbose=self._verbose)
error = self._verify_triton_state(client)
if error:
raise RuntimeError(f"Could not communicate to Triton Server: {error}")
LOGGER.debug(
f"Triton server {self._server_url} and model {self._model_name}:{self._model_version} " f"are up and ready!"
)
model_config = client.get_model_config(self._model_name, self._model_version)
model_metadata = client.get_model_metadata(self._model_name, self._model_version)
LOGGER.info(f"Model config {model_config}")
LOGGER.info(f"Model metadata {model_metadata}")
inputs = {tm.name: tm for tm in model_metadata.inputs}
outputs = {tm.name: tm for tm in model_metadata.outputs}
output_names = list(outputs)
outputs_req = [InferRequestedOutput(name) for name in outputs]
for ids, x, y_real in self._dataloader:
infer_inputs = []
for name in inputs:
data = x[name]
infer_input = InferInput(name, data.shape, inputs[name].datatype)
target_np_dtype = client_utils.triton_to_np_dtype(inputs[name].datatype)
data = data.astype(target_np_dtype)
infer_input.set_data_from_numpy(data)
infer_inputs.append(infer_input)
results = client.infer(
model_name=self._model_name,
model_version=self._model_version,
inputs=infer_inputs,
outputs=outputs_req,
client_timeout=self._response_wait_t,
)
y_pred = {name: results.as_numpy(name) for name in output_names}
yield ids, x, y_pred, y_real
def _verify_triton_state(self, triton_client):
if not triton_client.is_server_live():
return f"Triton server {self._server_url} is not live"
elif not triton_client.is_server_ready():
return f"Triton server {self._server_url} is not ready"
elif not triton_client.is_model_ready(self._model_name, self._model_version):
return f"Model {self._model_name}:{self._model_version} is not ready"
return None
class AsyncGRPCTritonRunner:
DEFAULT_MAX_RESP_WAIT_S = 120
DEFAULT_MAX_UNRESP_REQS = 128
DEFAULT_MAX_FINISH_WAIT_S = 900 # 15min
def __init__(
self,
server_url: str,
model_name: str,
model_version: str,
*,
dataloader,
verbose=False,
resp_wait_s: Optional[float] = None,
max_unresponded_reqs: Optional[int] = None,
):
self._server_url = server_url
self._model_name = model_name
self._model_version = model_version
self._dataloader = dataloader
self._verbose = verbose
self._response_wait_t = self.DEFAULT_MAX_RESP_WAIT_S if resp_wait_s is None else resp_wait_s
self._max_unresp_reqs = self.DEFAULT_MAX_UNRESP_REQS if max_unresponded_reqs is None else max_unresponded_reqs
self._results = queue.Queue()
self._processed_all = False
self._errors = []
self._num_waiting_for = 0
self._sync = threading.Condition()
self._req_thread = threading.Thread(target=self.req_loop, daemon=True)
def __iter__(self):
self._req_thread.start()
timeout_s = 0.050 # check flags processed_all and error flags every 50ms
while True:
try:
ids, x, y_pred, y_real = self._results.get(timeout=timeout_s)
yield ids, x, y_pred, y_real
except queue.Empty:
shall_stop = self._processed_all or self._errors
if shall_stop:
break
LOGGER.debug("Waiting for request thread to stop")
self._req_thread.join()
if self._errors:
error_msg = "\n".join(map(str, self._errors))
raise RuntimeError(error_msg)
def _on_result(self, ids, x, y_real, output_names, result, error):
with self._sync:
request_id = str(ids[0])
NOT_MATCHING_REQUEST_ID_MSG = (
"Error during processing result - request_id doesn't match. This shouldn't have happened."
)
if error:
response_id = error.get_response().id
if response_id != request_id:
raise RuntimeError(NOT_MATCHING_REQUEST_ID_MSG)
self._errors.append(error)
else:
response_id = result.get_response().id
if response_id != request_id:
raise RuntimeError(NOT_MATCHING_REQUEST_ID_MSG)
y_pred = {name: result.as_numpy(name) for name in output_names}
self._results.put((ids, x, y_pred, y_real))
self._num_waiting_for -= 1
self._sync.notify_all()
def req_loop(self):
client = InferenceServerClient(self._server_url, verbose=self._verbose)
self._errors = self._verify_triton_state(client)
if self._errors:
return
LOGGER.debug(
f"Triton server {self._server_url} and model {self._model_name}:{self._model_version} " f"are up and ready!"
)
model_config = client.get_model_config(self._model_name, self._model_version)
model_metadata = client.get_model_metadata(self._model_name, self._model_version)
LOGGER.info(f"Model config {model_config}")
LOGGER.info(f"Model metadata {model_metadata}")
inputs = {tm.name: tm for tm in model_metadata.inputs}
outputs = {tm.name: tm for tm in model_metadata.outputs}
output_names = list(outputs)
self._num_waiting_for = 0
for ids, x, y_real in self._dataloader:
infer_inputs = []
for name in inputs:
data = x[name]
infer_input = InferInput(name, data.shape, inputs[name].datatype)
target_np_dtype = client_utils.triton_to_np_dtype(inputs[name].datatype)
data = data.astype(target_np_dtype)
infer_input.set_data_from_numpy(data)
infer_inputs.append(infer_input)
outputs_req = [InferRequestedOutput(name) for name in outputs]
with self._sync:
def _check_can_send():
return self._num_waiting_for < self._max_unresp_reqs
can_send = self._sync.wait_for(_check_can_send, timeout=self._response_wait_t)
if not can_send:
error_msg = f"Runner could not send new requests for {self._response_wait_t}s"
self._errors.append(error_msg)
self._sync.notify_all()
break
request_id = str(ids[0])
callback = functools.partial(AsyncGRPCTritonRunner._on_result, self, ids, x, y_real, output_names)
client.async_infer(
model_name=self._model_name,
model_version=self._model_version,
inputs=infer_inputs,
outputs=outputs_req,
callback=callback,
request_id=request_id,
)
self._num_waiting_for += 1
self._sync.notify_all()
# wait till receive all requested data
with self._sync:
def _all_processed():
LOGGER.debug(f"wait for {self._num_waiting_for} unprocessed jobs")
return self._num_waiting_for == 0
self._processed_all = self._sync.wait_for(_all_processed, self.DEFAULT_MAX_FINISH_WAIT_S)
if not self._processed_all:
error_msg = f"Runner {self._response_wait_t}s timeout received while waiting for results from server"
self._errors.append(error_msg)
self._sync.notify_all()
LOGGER.debug("Finished request thread")
def _verify_triton_state(self, triton_client):
errors = []
if not triton_client.is_server_live():
errors.append(f"Triton server {self._server_url} is not live")
elif not triton_client.is_server_ready():
errors.append(f"Triton server {self._server_url} is not ready")
elif not triton_client.is_model_ready(self._model_name, self._model_version):
errors.append(f"Model {self._model_name}:{self._model_version} is not ready")
return errors
def _parse_args():
parser = argparse.ArgumentParser(description="Infer model on Triton server", allow_abbrev=False)
parser.add_argument(
"--server-url", type=str, default="localhost:8001", help="Inference server URL (default localhost:8001)"
)
parser.add_argument("--model-name", help="The name of the model used for inference.", required=True)
parser.add_argument("--model-version", help="The version of the model used for inference.", required=True)
parser.add_argument("--dataloader", help="Path to python file containing dataloader.", required=True)
parser.add_argument("--dump-labels", help="Dump labels to output dir", action="store_true", default=False)
parser.add_argument("--dump-inputs", help="Dump inputs to output dir", action="store_true", default=False)
parser.add_argument("-v", "--verbose", help="Verbose logs", action="store_true", default=True)
parser.add_argument("--output-dir", required=True, help="Path to directory where outputs will be saved")
parser.add_argument(
"--response-wait-time", required=False, help="Maximal time to wait for response", default=120, type=float
)
parser.add_argument(
"--max-unresponded-requests",
required=False,
help="Maximal number of unresponded requests",
default=128,
type=int,
)
parser.add_argument(
"--synchronous", help="Enable synchronous calls to Triton Server", action="store_true", default=False
)
args, *_ = parser.parse_known_args()
get_dataloader_fn = load_from_file(args.dataloader, label="dataloader", target=DATALOADER_FN_NAME)
ArgParserGenerator(get_dataloader_fn).update_argparser(parser)
args = parser.parse_args()
return args
def main():
args = _parse_args()
log_format = "%(asctime)s %(levelname)s %(name)s %(message)s"
log_level = logging.INFO if not args.verbose else logging.DEBUG
logging.basicConfig(level=log_level, format=log_format)
LOGGER.info("args:")
for key, value in vars(args).items():
LOGGER.info(f" {key} = {value}")
get_dataloader_fn = load_from_file(args.dataloader, label="dataloader", target=DATALOADER_FN_NAME)
dataloader_fn = ArgParserGenerator(get_dataloader_fn).from_args(args)
try:
if args.synchronous:
runner = SyncGRPCTritonRunner(
args.server_url,
args.model_name,
args.model_version,
dataloader=dataloader_fn(),
verbose=False,
resp_wait_s=args.response_wait_time,
)
else:
runner = AsyncGRPCTritonRunner(
args.server_url,
args.model_name,
args.model_version,
dataloader=dataloader_fn(),
verbose=False,
resp_wait_s=args.response_wait_time,
max_unresponded_reqs=args.max_unresponded_requests,
)
except Exception as e:
message = traceback.format_exc()
LOGGER.error(f"Encountered exception \n{message}")
raise e
with JsonDumpWriter(output_dir=args.output_dir) as writer:
start = time.time()
for ids, x, y_pred, y_real in tqdm(runner, unit="batch", mininterval=10):
data = _verify_and_format_dump(args, ids, x, y_pred, y_real)
writer.write(**data)
stop = time.time()
LOGGER.info(f"\nThe inference took {stop - start:0.3f}s")
def _verify_and_format_dump(args, ids, x, y_pred, y_real):
data = {"outputs": y_pred, "ids": {"ids": ids}}
if args.dump_inputs:
data["inputs"] = x
if args.dump_labels:
if not y_real:
raise ValueError(
"Found empty label values. Please provide labels in dataloader_fn or do not use --dump-labels argument"
)
data["labels"] = y_real
return data
if __name__ == "__main__":
main()
|
PyTorch/Segmentation/MaskRCNN | MaskRCNN | README | # Mask R-CNN For PyTorch
This repository provides a script and recipe to train and infer on MaskRCNN to achieve state of the art accuracy, and is tested and maintained by NVIDIA.
## Table Of Contents
* [Model overview](#model-overview)
* [Model Architecture](#model-architecture)
* [Default configuration](#default-configuration)
* [Feature support matrix](#feature-support-matrix)
* [Features](#features)
* [Mixed precision training](#mixed-precision-training)
* [Enabling mixed precision](#enabling-mixed-precision)
* [Enabling TF32](#enabling-tf32)
* [Performance Optimizations](#performance-optimizations)
* [Setup](#setup)
* [Requirements](#requirements)
* [Quick start guide](#quick-start-guide)
* [Advanced](#advanced)
* [Scripts and sample code](#scripts-and-sample-code)
* [Parameters](#parameters)
* [Command line options](#command-line-options)
* [Getting the data](#getting-the-data)
* [Dataset guidelines](#dataset-guidelines)
* [Training process](#training-process)
* [Performance](#performance)
* [Benchmarking](#benchmarking)
* [Training performance benchmark](#training-performance-benchmark)
* [Inference performance benchmark](#inference-performance-benchmark)
* [Results](#results)
* [Training accuracy results](#training-accuracy-results)
* [Training accuracy: NVIDIA DGX A100 (8x A100 80GB)](#training-accuracy-nvidia-dgx-a100-8x-a100-80gb)
* [Training accuracy: NVIDIA DGX-1 (8x V100 32GB)](#training-accuracy-nvidia-dgx-1-8x-v100-32gb)
* [Training loss curves](#training-loss-curves)
* [Training stability test](#training-stability-test)
* [Training performance results](#training-performance-results)
* [Training performance: NVIDIA DGX A100 (8x A100 80GB)](#training-performance-nvidia-dgx-a100-8x-a100-80gb)
* [Training performance: NVIDIA DGX-1 (8x V100 32GB)](#training-performance-nvidia-dgx-1-8x-v100-32gb)
* [Inference performance results](#inference-performance-results)
* [Inference performance: NVIDIA DGX A100 (1x A100 80GB)](#inference-performance-nvidia-dgx-a100-1x-a100-80gb)
* [Inference performance: NVIDIA DGX-1 (1x V100 32GB)](#inference-performance-nvidia-dgx-1-1x-v100-32gb)
* [Release notes](#release-notes)
* [Changelog](#changelog)
* [Known issues](#known-issues)
## Model overview
Mask R-CNN is a convolution based neural network for the task of object instance segmentation. The paper describing the model can be found [here](https://arxiv.org/abs/1703.06870). NVIDIA’s Mask R-CNN is an optimized version of [Facebook’s implementation](https://github.com/facebookresearch/maskrcnn-benchmark).This model is trained with mixed precision using Tensor Cores on Volta, Turing, and the NVIDIA Ampere GPU architectures. Therefore, researchers can get results 1.3x faster than training without Tensor Cores, while experiencing the benefits of mixed precision training. This model is tested against each NGC monthly container release to ensure consistent accuracy and performance over time.
The repository also contains scripts to interactively launch training, benchmarking and inference routines in a Docker container.
The major differences between the official implementation of the paper and our version of Mask R-CNN are as follows:
- Mixed precision support with [PyTorch AMP](https://pytorch.org/docs/stable/amp.html).
- Gradient accumulation to simulate larger batches.
- Custom fused CUDA kernels for faster computations.
These techniques/optimizations improve model performance and reduce training time by a factor of 1.3x, allowing you to perform more efficient instance segmentation with no additional effort.
Other publicly available implementations of Mask R-CNN include:
- [NVIDIA TensorFlow](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow/Segmentation/MaskRCNN)
- [NVIDIA TensorFlow2](https://github.com/NVIDIA/DeepLearningExamples/tree/master/TensorFlow2/Segmentation/MaskRCNN)
- [Matterport](https://github.com/matterport/Mask_RCNN)
- [Tensorpack](https://github.com/tensorpack/tensorpack/tree/master/examples/FasterRCNN)
- [Google’s tensorflow model](https://github.com/tensorflow/models/tree/master/research/object_detection)
### Model architecture
Mask R-CNN builds on top of FasterRCNN adding an additional mask head for the task of image segmentation.
The architecture consists of following:
- R-50 backbone with FPN
- RPN head
- RoI ALign
- Bounding and classification box head
- Mask head
### Default Configuration
The default configuration of this model can be found at `pytorch/maskrcnn_benchmark/config/defaults.py`. The default hyper-parameters are as follows:
- General:
- Base Learning Rate set to 0.001
- Global batch size set to 16 images
- Steps set to 30000
- Images re-sized with aspect ratio maintained and smaller side length between [800,1333]
- Global train batch size - 16
- Global test batch size - 8
- Feature extractor:
- Backend network set to Resnet50_conv4
- First two blocks of backbone network weights are frozen
- Region Proposal Network (RPN):
- Anchor stride set to 16
- Anchor sizes set to (32, 64, 128, 256, 512)
- Foreground IOU Threshold set to 0.7, Background IOU Threshold set to 0.5
- RPN target fraction of positive proposals set to 0.5
- Train Pre-NMS Top proposals set to 12000
- Train Post-NMS Top proposals set to 2000
- Test Pre-NMS Top proposals set to 6000
- Test Post-NMS Top proposals set to 1000
- RPN NMS Threshold set to 0.7
- RoI heads:
- Foreground threshold set to 0.5
- Batch size per image set to 512
- Positive fraction of batch set to 0.25
This repository implements multi-gpu and gradient accumulation to support larger batches and mixed precision support. This implementation also includes the following optimizations.
- Target generation - Optimized GPU implementation for generating binary mask ground truths from the list of polygon coordinates that exist in the dataset.
- Custom CUDA kernels for:
- Box Intersection over Union (IoU) computation
- Proposal matcher
- Generate anchor boxes
- Pre NMS box selection - Selection of RoIs based on objectness score before NMS is applied.
The source files can be found under `maskrcnn_benchmark/csrc/cuda`.
### Feature support matrix
The following features are supported by this model.
| **Feature** | **Mask R-CNN** |
|:---------:|:----------:|
|Native AMP|Yes|
|Native DDP|Yes|
|Native NHWC|Yes|
#### Features
[AMP](https://pytorch.org/docs/stable/amp.html) is an abbreviation used for automatic mixed precision training.
[Native DDP](https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html); [Apex DDP](https://nvidia.github.io/apex/parallel.html) where DDP stands for DistributedDataParallel and is used for multi-GPU training.
[NHWC](https://pytorch.org/tutorials/intermediate/memory_format_tutorial.html) is the channels last memory format for tensors.
### Mixed precision training
Mixed precision is the combined use of different numerical precisions in a computational method. [Mixed precision](https://arxiv.org/abs/1710.03740) training offers significant computational speedup by performing operations in half-precision format, while storing minimal information in single-precision to retain as much information as possible in critical parts of the network. Since the introduction of [tensor cores](https://developer.nvidia.com/tensor-cores) in the Volta, and following with both the Turing and Ampere architectures, significant training speedups are experienced by switching to mixed precision -- up to 3x overall speedup on the most arithmetically intense model architectures. Using mixed precision training requires two steps:
1. Porting the model to use the FP16 data type where appropriate.
2. Adding loss scaling to preserve small gradient values.
For information about:
- How to train using mixed precision, see the [Mixed Precision Training](https://arxiv.org/abs/1710.03740) paper and [Training With Mixed Precision](https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html) documentation.
- Techniques used for mixed precision training, see the [Mixed-Precision Training of Deep Neural Networks](https://devblogs.nvidia.com/mixed-precision-training-deep-neural-networks/) blog.
#### Enabling mixed precision
In this repository, mixed precision training is enabled by the [PyTorch native AMP](https://pytorch.org/docs/stable/amp.html) library. PyTorch has an automatic mixed precision module that allows mixed precision to be enabled with minimal code changes.
Automatic mixed precision can be enabled with the following code changes:
```
# Create gradient scaler
scaler = torch.cuda.amp.GradScaler(init_scale=8192.0)
# Wrap the forward pass in torch.cuda.amp.autocast
with torch.cuda.amp.autocast():
loss_dict = model(images, targets)
# Gradient scaling
scaler.scale(losses).backward()
scaler.step(optimizer)
scaler.update()
```
AMP can be enabled by setting `DTYPE` to `float16`.
#### Enabling TF32
TensorFloat-32 (TF32) is the new math mode in [NVIDIA A100](https://www.nvidia.com/en-us/data-center/a100/) GPUs for handling the matrix math also called tensor operations. TF32 running on Tensor Cores in A100 GPUs can provide up to 10x speedups compared to single-precision floating-point math (FP32) on Volta GPUs.
TF32 Tensor Cores can speed up networks using FP32, typically with no loss of accuracy. It is more robust than FP16 for models which require high dynamic range for weights or activations.
For more information, refer to the [TensorFloat-32 in the A100 GPU Accelerates AI Training, HPC up to 20x](https://blogs.nvidia.com/blog/2020/05/14/tensorfloat-32-precision-format/) blog post.
TF32 is supported in the NVIDIA Ampere GPU architecture and is enabled by default.
### Performance Optimizations
[MLPerf Training](https://mlcommons.org/en/training-normal-11/) is an [ML Commons](https://mlcommons.org/en/) benchmark that measures how fast systems can train models to a target quality metric. MaskRCNN is one of the MLPerf training benchmarks which is improved every year. Some of the performance optimizations used in MLPerf can be introduced to this repository easily to gain significant training speedup. [Here](https://github.com/mlcommons/training_results_v1.1/tree/main/NVIDIA/benchmarks/maskrcnn/implementations/pytorch) is NVIDIA's MLPerf v1.1 submission codebase.
Listed below are some of the performance optimization tricks applied to this repository:
- Prefetcher: [PyTorch CUDA Streams](https://pytorch.org/docs/stable/generated/torch.cuda.Stream.html) are used to fetch the data required for the next iteration during the current iteration to reduce dataloading time before each iteration.
- pin_memory: Setting pin_memory can speed up host to device transfer of samples in dataloader. More details can be found in [this blog](https://developer.nvidia.com/blog/how-optimize-data-transfers-cuda-cc/).
- Hybrid Dataloader: Some dataloading is done on the CPU and the rest is on the GPU.
- FusedSGD: Replace SGD with Apex FusedSGD for training speedup.
- Native DDP: Use PyTorch [DistributedDataParallel](https://pytorch.org/tutorials/intermediate/ddp_tutorial.html).
- Native NHWC: Switching from channels first (NCHW) memory format to NHWC (channels last) gives [better performance](https://docs.nvidia.com/deeplearning/performance/dl-performance-convolutional/index.html#tensor-layout).
Increasing the local batch size and applying the above tricks gives ~2x speedup for end-to-end training time on 8 DGX A100s when compared to the old implementation.
## Setup
The following sections list the requirements in order to start training the Mask R-CNN model.
### Requirements
This repository contains `Dockerfile` which extends the PyTorch NGC container and encapsulates some dependencies. Aside from these dependencies, ensure you have the following components:
- [NVIDIA Docker](https://github.com/NVIDIA/nvidia-docker)
- [PyTorch 21.12-py3 NGC container](https://ngc.nvidia.com/registry/nvidia-pytorch)
- Supported GPUs:
- [NVIDIA Volta architecture](https://www.nvidia.com/en-us/data-center/volta-gpu-architecture/)
- [NVIDIA Turing architecture](https://www.nvidia.com/en-us/geforce/turing/)
- [NVIDIA Ampere architecture](https://www.nvidia.com/en-us/data-center/nvidia-ampere-gpu-architecture/)
For more information about how to get started with NGC containers, see the
following sections from the NVIDIA GPU Cloud Documentation and the Deep Learning
Documentation:
- [Getting Started Using NVIDIA GPU Cloud](https://docs.nvidia.com/ngc/ngc-getting-started-guide/index.html)
- [Accessing And Pulling From The NGC Container Registry](https://docs.nvidia.com/deeplearning/dgx/user-guide/index.html#accessing_registry)
- [Running PyTorch](https://docs.nvidia.com/deeplearning/dgx/pytorch-release-notes/running.html#running)
For those unable to use the [framework name] NGC container, to set up the required environment or create your own container, see the versioned [NVIDIA Container Support Matrix](https://docs.nvidia.com/deeplearning/frameworks/support-matrix/index.html).
## Quick Start Guide
To train your model using mixed or TF32 precision with Tensor Cores or using FP32, perform the following steps using the default parameters of the Mask R-CNN model on the COCO 2017 dataset. For the specifics concerning training and inference, see the [Advanced](#advanced) section.
### 1. Clone the repository.
```
git clone https://github.com/NVIDIA/DeepLearningExamples.git
cd DeepLearningExamples/PyTorch/Segmentation/MaskRCNN
```
### 2. Download and preprocess the dataset.
This repository provides scripts to download and extract the COCO 2017 dataset. Data will be downloaded to the `current working` directory on the host and extracted to a user-defined directory
To download, verify, and extract the COCO dataset, use the following scripts:
```
./download_dataset.sh <data/dir>
```
By default, the data is organized into the following structure:
```
<data/dir>
annotations/
instances_train2017.json
instances_val2017.json
train2017/
*.jpg
val2017/
*.jpg
```
### 3. Build the Mask R-CNN PyTorch NGC container.
```
cd pytorch/
bash scripts/docker/build.sh
```
### 4. Start an interactive session in the NGC container to run training/inference.
After you build the container image, you can start an interactive CLI session with
```
bash scripts/docker/interactive.sh <path/to/dataset/>
```
The `interactive.sh` script requires that the location on the dataset is specified. For example, `/home/<USER>/Detectron_PyT/detectron/lib/datasets/data/coco`
### 5. Start training.
```
bash scripts/train.sh
```
The `train.sh` script trains a model and performs evaluation on the COCO 2014 dataset. By default, the training script:
- Uses 8 GPUs.
- Saves a checkpoint every 2500 iterations and at the end of training. All checkpoints, evaluation results and training logs are saved to the `/results` directory (in the container which can be mounted to a local directory).
- Mixed precision training with Tensor Cores is invoked by either adding `--amp` to the command line or `DTYPE \"float16\"` to the end of the above command as shown in the train script. This will override the default `DTYPE` configuration which is tf32 for Ampere and float32 for Volta.
- Channels last memory format can be set using the `NHWC` flag which is set to `True` by default. Disabling this flag will run training using `NCHW` or channels first memory format.
The `scripts/train.sh` script runs the following Python command:
```
python -m torch.distributed.launch --nproc_per_node=8 tools/train_net.py --config-file “configs/e2e_mask_rcnn_R_50_FPN_1x.yaml”
```
### 6. Start validation/evaluation.
```
bash scripts/eval.sh
```
Model evaluation on a checkpoint can be launched by running the `pytorch/scripts/eval.sh` script. The script requires:
- the location of the checkpoint folder to be specified and present within/mounted to the container.
- a text file named last_checkpoint which contains the path to the latest checkpoint. This mechanism is required in order to resume training from the latest checkpoint.
- The file last_checkpoint is automatically created at the end of the training process.
By default, evaluation is performed on the test dataset once training is complete. To skip evaluation at the end of training, issue the `--skip-test` flag.
Additionally, to perform evaluation after every epoch and terminate training on reaching a minimum required mAP score, set
- `PER_EPOCH_EVAL = True`
- `MIN_BBOX_MAP = <required value>`
- `MIN_MASK_MAP = <required value>`
### 7. Start inference/predictions.
Model predictions can be obtained on a test dataset and a model checkpoint by running the `scripts/inference.sh <config/file/path>` script. The script requires:
- the location of the checkpoint folder and dataset to be specified and present within/mounted to the container.
- a text file named last_checkpoint which contains the path to the checkpoint.
For example:
```
bash scripts/inference.sh configs/e2e_mask_rcnn_R_50_FPN_1x.yaml
```
Model prediction files get saved in the `<OUTPUT_DIR>/inference` directory and correspond to:
```
bbox.json - JSON file containing bounding box predictions
segm.json - JSON file containing mask predictions
predictions.pth - All prediction tensors computed by the model in torch.save() format
coco_results.pth - COCO evaluation results in torch.save() format - if --skip-eval is not used in the script above
```
To perform inference and skip computation of mAP scores, issue the `--skip-eval` flag. Performance is reported in seconds per iteration per GPU. The benchmarking scripts can be used to extract frames per second on training and inference.
## Advanced
The following sections provide greater details of the dataset, running training and inference, and the training results.
### Scripts and sample code
Descriptions of the key scripts and folders are provided below.
- maskrcnn_benchmark - Contains scripts to build individual components of the model such as backbone, FPN, RPN, mask and bbox heads etc.,
- download_dataset.sh - Launches download and processing of required datasets.
- scripts/ - Contains shell scripts to launch data download, train the model and perform inferences.
- train.sh - Launches model training
- eval.sh - Performs inference and computes mAP of predictions.
- inference.sh - Performs inference on given data.
- train_benchmark.sh - To benchmark training performance.
- inference_benchmark.sh - To benchmark inference performance.
- docker/ - Scripts to build the docker image and to start an interactive session.
- tools/
- train_net.py - End to end to script to load data, build and train the model.
- test_net.py - End to end script to load data, checkpoint and perform inference and compute mAP score.
### Parameters
#### train_net.py script parameters
You can modify the training behaviour through the various flags in both the `train_net.py` script and through overriding specific parameters in the YAML config files. Flags in the `train_net.py` script are as follows:
`--config_file` - path to config file containing model params
`--skip-test` - skips model testing after training
`--opts` - allows for you to override specific params in config file
For example:
```
python -m torch.distributed.launch --nproc_per_node=2 tools/train_net.py \
--config-file configs/e2e_faster_rcnn_R_50_FPN_1x.yaml \
DTYPE "float16" \
NHWC True \
OUTPUT_DIR RESULTS \
SOLVER.BASE_LR 0.002 \
SOLVER.STEPS ‘(360000, 480000)’
```
### Command-line options
To see the full list of available options and their descriptions, use the -h or --help command line option, for example:
`python tools/train_net.py --help`
### Getting the data
The Mask R-CNN model was trained on the [COCO 2017](http://cocodataset.org/#download) dataset. This dataset comes with a training and validation set.
This repository contains the `./download_dataset.sh`,`./verify_dataset.sh`, and `./extract_dataset.sh` scripts which automatically download and preprocess the training and validation sets.
#### Dataset guidelines
In order to run on your own dataset, ensure your dataset is present/mounted to the Docker container with the following hierarchy:
```
my_dataset/
images_train/
images_val/
instances_train.json
instances_val.json
```
and add it to `DATASETS` dictionary in `maskrcnn_benchmark/config/paths_catalog.py`
```
DATASETS = {
"my_dataset_train": {
"img_dir": "data/images_train",
"ann_file": "data/instances_train.json"
},
"my_dataset_val": {
"img_dir": "data/images_val",
"ann_file": "data/instances_val.json"
},
}
```
```
python -m torch.distributed.launch --nproc_per_node=<NUM_GPUS> tools/train_net.py \
--config-file <CONFIG? \
DATASETS.TRAIN "(\"my_dataset_train\")"\
DATASETS.TEST "(\"my_dataset_val\")"\
DTYPE "float16" \
OUTPUT_DIR <RESULTS> \
| tee <LOGFILE>
```
### Training Process
Training is performed using the `tools/train_net.py` script along with parameters defined in the config file. The default config files can be found in the `pytorch/configs/` directory.
The `e2e_mask_rcnn_R_50_FPN_1x.yaml` file was used to gather accuracy and performance metrics. This configuration sets the following parameters:
- Backbone weights to ResNet-50
- Feature extractor set to ResNet-50 with Feature Pyramid Networks (FPN)
- RPN uses FPN
- RoI Heads use FPN
- Dataset - COCO 2017
- Base Learning Rate - 0.12
- Global train batch size - 96
- Global test batch size - 8
- RPN batch size - 256
- ROI batch size - 512
- Solver steps - (12000, 16000)
- Max iterations - 16667
- Warmup iterations - 800
- Warmup factor = 0.0001
- Initial learning rate = Base Learning Rate x Warmup factor
The default feature extractor can be changed by setting `CONV_BODY` parameter in `yaml` file to any of the following:
- R-50-C4
- R-50-C5
- R-101-C4
- R-101-C5
- R-101-FPN
The default backbone can be changed to a flavor of Resnet-50 or ResNet-101 by setting `WEIGHT` parameter in `yaml` file to any of the following:
- "catalog://ImageNetPretrained/MSRA/R-50-GN"
- "catalog://ImageNetPretrained/MSRA/R-101"
- "catalog://ImageNetPretrained/MSRA/R-101-GN"
This script outputs results to the current working directory by default. However, this can be changed by adding `OUTPUT_DIR <DIR_NAME>` to the end of the default command. Logs produced during training are also stored in the `OUTPUT_DIR` specified. The training log will contain information about:
- Loss, time per iteration, learning rate and memory metrics
- performance values such as time per step
- test accuracy and test performance values after evaluation
The training logs are located in the `<OUTPUT_DIR>/log` directory. The summary after each training epoch is printed in the following format:
```
INFO:maskrcnn_benchmark.trainer:eta: 4:42:15 iter: 20 loss: 1.8236 (2.7274) loss_box_reg: 0.0249 (0.0620) loss_classifier: 0.6086 (1.2918) loss_mask: 0.6996 (0.8026) loss_objectness: 0.5373 (0.4787) loss_rpn_box_reg: 0.0870 (0.0924) time: 0.2002 (0.3765) data: 0.0099 (0.1242) lr: 0.014347 max mem: 3508
```
The mean and median training losses are reported every 20 steps.
Multi-gpu and multi-node training is enabled with the PyTorch distributed launch module. The following example runs training on 8 GPUs:
```
python -m torch.distributed.launch --nproc_per_node=8 tools/train_net.py --config-file \"configs/e2e_mask_rcnn_R_50_FPN_1x.yaml\"
```
We have tested batch sizes upto 12 on a 32GB V100 and 80GB A100 with mixed precision. The repository also implements gradient accumulation functionality to simulate bigger batches as follows:
```
python -m torch.distributed.launch --nproc_per_node=8 tools/train_net.py --config-file \"configs/e2e_mask_rcnn_R_50_FPN_1x.yaml\" SOLVER.ACCUMULATE_GRAD True SOLVER.ACCUMULATE_STEPS 4
```
By default, training is performed using FP32 on Volta and TF32 on Ampere, however training time can be reduced further using tensor cores and mixed precision. This can be done by either adding `--amp` to the command line or `DTYPE \"float16\"` to override the respective parameter in the config file.
__Note__: When training a global batch size >= 32, it is recommended to add required warmup by additionally setting the following parameters:
- `SOLVER.WARMUP_ITERS 625`
- `SOLVER.WARMUP_FACTOR 0.01`
When experimenting with different global batch sizes for training and inference, make sure `SOLVER.IMS_PER_BATCH` and `TEST.IMS_PER_BATCH` are divisible by the number of GPUs.
#### Other training options
A sample single GPU config is provided under `configs/e2e_mask_rcnn_R_50_FPN_1x_1GPU.yaml`
To train with smaller global batch sizes (32 or 64) use `configs/e2e_mask_rcnn_R_50_FPN_1x_bs32.yaml` and `configs/e2e_mask_rcnn_R_50_FPN_1x_bs64.yaml` respectively.
For multi-gpu runs, `-m torch.distributed.launch --nproc_per_node num_gpus` is added prior to `tools/train_net.py`. For example, for an 8 GPU run:
```
python -m torch.distributed.launch --nproc_per_node=8 tools/train_net.py --config-file “configs/e2e_mask_rcnn_R_50_FPN_1x.yaml”
```
Training is terminated when either the required accuracies specified on the command line are reached or if the number of training iterations specified is reached.
To terminate training on reaching target accuracy on 8 GPUs, run:
```
python -m torch.distributed.launch --nproc_per_node=8 tools/train_net.py --config-file “configs/e2e_mask_rcnn_R_50_FPN_1x.yaml” PER_EPOCH_EVAL True MIN_BBOX_MAP 0.377 MIN_MASK_MAP 0.342
```
__Note__: The score is always the Average Precision(AP) at
- IoU = 0.50:0.95
- Area = all - include small, medium and large
- maxDets = 100
## Performance
### Benchmarking
Benchmarking can be performed for both training and inference. Both scripts run the Mask R-CNN model using the parameters defined in `configs/e2e_mask_rcnn_R_50_FPN_1x.yaml`. You can specify whether benchmarking is performed in FP16, TF32 or FP32 by specifying it as an argument to the benchmarking scripts.
#### Training performance benchmark
Training benchmarking can performed by running the script:
```
scripts/train_benchmark.sh <float16/tf32/float32> <number of gpus> <NHWC True/False> <Hybrid dataloader True/False>
```
#### Inference performance benchmark
Inference benchmarking can be performed by running the script:
```
scripts/inference_benchmark.sh <float16/tf32/float32> <batch_size>
```
### Results
The following sections provide details on how we achieved our performance and accuracy in training and inference.
#### Training Accuracy Results
##### Training accuracy: NVIDIA DGX A100 (8x A100 80GB)
Our results were obtained by running the `scripts/train.sh` training script in the 21.12-py3 NGC container on NVIDIA DGX A100 (8x A100 80GB) GPUs.
| GPUs | Batch size / GPU | BBOX mAP - TF32| MASK mAP - TF32 | BBOX mAP - FP16| MASK mAP - FP16 | Time to train - TF32 | Time to train - mixed precision | Time to train speedup (TF32 to mixed precision)
| --| --| -- | -- | -- | -- | -- | -- | --
| 8 | 12 | 0.3765 | 0.3408 | 0.3763 | 0.3417 | 2.15 | 1.85 | 1.16x
##### Training accuracy: NVIDIA DGX-1 (8x V100 32GB)
Our results were obtained by running the `scripts/train.sh` training script in the PyTorch 21.12-py3 NGC container on NVIDIA DGX-1 with 8x V100 32GB GPUs.
| GPUs | Batch size / GPU | BBOX mAP - FP32| MASK mAP - FP32 | BBOX mAP - FP16| MASK mAP - FP16 | Time to train - FP32 | Time to train - mixed precision | Time to train speedup (FP32 to mixed precision)
| --| --| -- | -- | -- | -- | -- | -- | --
| 8 | 12 | 0.3768 | 0.3415 | 0.3755 | 0.3403 | 5.58 | 3.37 | 1.65x
Note: Currently V100 32GB + FP32 + NHWC + Hybrid dataloader causes a slowdown. So for all V100 32GB FP32 runs hybrid dataloader and NHWC are disabled `NHWC=False HYBRID=False DTYPE=float32 bash scripts/train.sh`
##### Training loss curves
![Loss Curve](./img/loss_curve.png)
Here, multihead loss is simply the summation of losses on the mask head and the bounding box head.
##### Training Stability Test
The following tables compare mAP scores across 5 different training runs with different seeds. The runs showcase consistent convergence on all 5 seeds with very little deviation.
| **Config** | **Seed 1** | **Seed 2** | **Seed 3** | **Seed 4** | **Seed 5** | **Mean** | **Standard Deviation** |
| --- | --- | ----- | ----- | --- | --- | ----- | ----- |
| 8 GPUs, final AP BBox | 0.3764 | 0.3766 | 0.3767 | 0.3752 | 0.3768 | 0.3763 | 0.0006 |
| 8 GPUs, final AP Segm | 0.3414 | 0.3411 | 0.341 | 0.3407 | 0.3415 | 0.3411 | 0.0003 |
#### Training Performance Results
##### Training performance: NVIDIA DGX A100 (8x A100 80GB)
Our results were obtained by running the `scripts/train_benchmark.sh` training script in the 21.12-py3 NGC container on NVIDIA DGX A100 (8x A100 80GB) GPUs. Performance numbers in images per second were averaged over 500 iterations.
| GPUs | Batch size / GPU | Throughput - TF32 | Throughput - mixed precision | Throughput speedup (TF32 - mixed precision) | Weak scaling - TF32 | Weak scaling - mixed precision
--- | --- | ----- | ----- | --- | --- | ----- |
| 1 | 12 | 23 | 24 | 1.04 | 1 | 1 |
| 4 | 12 | 104 | 106 | 1.02 | 4.52 | 4.42 |
| 8 | 12 | 193 | 209 | 1.08 | 8.39 | 8.71 |
##### Training performance: NVIDIA DGX-1 (8x V100 32GB)
Our results were obtained by running the `scripts/train_benchmark.sh` training script in the 21.12-py3 NGC container on NVIDIA DGX-1 with (8x V100 32GB) GPUs. Performance numbers in images per second were averaged over 500 iterations.
| GPUs | Batch size / GPU | Throughput - FP32 | Throughput - mixed precision | Throughput speedup (FP32 - mixed precision) | Weak scaling - FP32 | Weak scaling - mixed precision
| --- | --- | ----- | ----- | --- | --- | -----
| 1 | 12 | 12 | 16 | 1.33 | 1 | 1 |
| 4 | 12 | 44 | 71 | 1.61 | 3.67 | 4.44 |
| 8 | 12 | 85 | 135 | 1.59 | 7.08 | 8.44 |
Note: Currently V100 32GB + FP32 + NHWC + Hybrid dataloader causes a slowdown. So for all V100 32GB FP32 runs hybrid dataloader and NHWC are disabled `bash scripts/train_benchmark.sh fp32 <number of gpus> False False`
To achieve these same results, follow the steps in the [Quick Start Guide](#quick-start-guide).
#### Inference performance results
##### Inference performance: NVIDIA DGX A100 (1x A100 80GB)
Our results were obtained by running the `scripts/inference_benchmark.sh` training script in the PyTorch 21.12-py3 NGC container on NVIDIA DGX A100 (1x A100 80GB) GPU.
FP16 Inference Latency
| Batch size | Throughput Avg | Latency Avg (ms) | Latency 90% (ms) | Latency 95% (ms) | Latency 99% (ms)
| --- | ----- | ----- | ----- | ----- | ----- |
| 1 | 23 | 34.91 | 33.87 | 33.95 | 34.15 |
| 2 | 26 | 59.31 | 57.80 | 57.99 | 58.27 |
| 4 | 31 | 101.46 | 99.24 | 99.51 | 99.86 |
| 8 | 31 | 197.57 | 193.82 | 194.28 | 194.77 |
TF32 Inference Latency
| Batch size | Throughput Avg | Latency Avg (ms) | Latency 90% (ms) | Latency 95% (ms) | Latency 99% (ms)
| --- | ----- | ----- | ----- | ----- | ----- |
| 1 | 25 | 31.66 | 31.03 | 31.13 | 31.26 |
| 2 | 28 | 56.91 | 55.88 | 56.05 | 56.02 |
| 4 | 29 | 104.11 | 102.29 | 102.53 | 102.74 |
| 8 | 30 | 201.13 | 197.43 | 197.84 | 198.19 |
##### Inference performance: NVIDIA DGX-1 (1x V100 32GB)
Our results were obtained by running the `scripts/inference_benchmark.sh` training script in the PyTorch 21.12-py3 NGC container on NVIDIA DGX-1 with 1x V100 32GB GPUs.
FP16 Inference Latency
| Batch size | Throughput Avg | Latency Avg (ms) | Latency 90% (ms) | Latency 95% (ms) | Latency 99% (ms)
| --- | ----- | ----- | ----- | ----- | ----- |
| 1 | 19 | 44.72 | 43.62 | 43.77 | 44.03 |
| 2 | 21 | 82.80 | 81.37 | 81.67 | 82.06 |
| 4 | 22 | 155.25 | 153.15 | 153.63 | 154.10 |
| 8 | 22 | 307.60 | 304.08 | 304.82 | 305.48 |
FP32 Inference Latency
| Batch size | Throughput Avg | Latency Avg (ms) | Latency 90% (ms) | Latency 95% (ms) | Latency 99% (ms)
| --- | ----- | ----- | ----- | ----- | ----- |
| 1 | 16 | 52.78 | 51.87 | 52.16 | 52.43 |
| 2 | 17 | 100.81 | 99.19 | 99.67 | 100.15 |
| 4 | 17 | 202.05 | 198.84 | 199.98 | 200.92 |
| 8 | 18 | 389.99 | 384.29 | 385.77 | 387.66 |
To achieve these same results, follow the steps in the [Quick Start Guide](#quick-start-guide).
## Release notes
### Changelog
May 2022
- Update container to 21.12
- Add native NHWC, native DDP
- Replace SGD with FusedSGD
- Use cuda streams to prefetch dataloader
- Hybrid dataloader
- Use new training recipe
October 2021
- Replace APEX AMP with PyTorch native AMP
- Use opencv-python version 4.4.0.42
July 2021
- Update container
- Use native AMP
- Update dataset to coco 2017
June 2020
- Updated accuracy and performance tables to include A100 results
September 2019
- Updates for PyTorch 1.2
- Jupyter notebooks added
July 2019
- Update AMP to new API
- Update README
- Download support from torch hub
- Update default test batch size to 1/gpu
March 2019
- Initial release
### Known Issues
Currently V100 32GB + FP32 + NHWC + Hybrid dataloader causes a slowdown. So for all V100 32GB FP32 runs hybrid dataloader and NHWC should be disabled.
|
PyTorch/LanguageModeling/BERT/triton/deployment_toolkit/bermuda | bermuda | utils | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import Counter
from typing import Callable, Dict, List, Optional
import networkx as nx
from ..core import ShapeSpec
def infer_precision(
nx_graph: nx.Graph,
input_names: List[str],
output_names: List[str],
get_node_dtype_fn: Callable,
):
node_dtypes = [nx_graph.nodes[node_name].get("dtype", None) for node_name in nx_graph.nodes]
node_dtypes = [dt for dt in node_dtypes if dt is None or dt.kind not in ["i", "b"]]
dtypes_counter = Counter(node_dtypes)
return dtypes_counter.most_common()[0][0]
def get_shapes_with_dynamic_axes(dataloader, batch_size_dim: Optional[int] = None):
def _set_dynamic_shapes(t, shapes):
for k, v in t.items():
shape = list(v.shape)
for dim, s in enumerate(shape):
if shapes[k][dim] != -1 and shapes[k][dim] != s:
shapes[k][dim] = -1
def _mark_batch_axis(shape, batch_axis: int):
shape = list(shape)
shape[batch_axis] = -1
return tuple(shape)
## get all shapes from input and output tensors
input_shapes = {}
output_shapes = {}
for batch in dataloader:
_, x, y = batch
for k, v in x.items():
input_shapes[k] = list(v.shape)
for k, v in y.items():
output_shapes[k] = list(v.shape)
break
# based on max <max_num_iters> iterations, check which
# dimensions differ to determine dynamic_axes
max_num_iters = 100
for idx, batch in enumerate(dataloader):
if idx >= max_num_iters:
break
_, x, y = batch
_set_dynamic_shapes(x, input_shapes)
_set_dynamic_shapes(y, output_shapes)
if batch_size_dim is not None:
input_shapes = {name: _mark_batch_axis(shape, batch_size_dim) for name, shape in input_shapes.items()}
output_shapes = {name: _mark_batch_axis(shape, batch_size_dim) for name, shape in output_shapes.items()}
return input_shapes, output_shapes
def get_dynamic_axes(dataloader, batch_size_dim: Optional[int] = None):
input_shapes, output_shapes = get_shapes_with_dynamic_axes(dataloader, batch_size_dim=batch_size_dim)
all_shapes = {**input_shapes, **output_shapes}
dynamic_axes = {}
for k, shape in all_shapes.items():
for idx, s in enumerate(shape):
if s == -1:
dynamic_axes[k] = {idx: k + "_" + str(idx)}
for k in all_shapes:
if k in dynamic_axes:
dynamic_axes[k].update({batch_size_dim: "batch_size_" + str(batch_size_dim)})
elif batch_size_dim is not None:
dynamic_axes[k] = {batch_size_dim: "batch_size_" + str(batch_size_dim)}
return dynamic_axes
def get_input_shapes(dataloader, max_batch_size=1) -> Dict[str, ShapeSpec]:
def init_counters_and_shapes(x, counters, min_shapes, max_shapes):
for k, v in x.items():
counters[k] = Counter()
min_shapes[k] = [float("inf")] * v.ndim
max_shapes[k] = [float("-inf")] * v.ndim
counters = {}
min_shapes: Dict[str, tuple] = {}
max_shapes: Dict[str, tuple] = {}
for idx, batch in enumerate(dataloader):
ids, x, y = batch
if idx == 0:
init_counters_and_shapes(x, counters, min_shapes, max_shapes)
for k, v in x.items():
shape = v.shape
counters[k][shape] += 1
min_shapes[k] = tuple(min(a, b) for a, b in zip(min_shapes[k], shape))
max_shapes[k] = tuple(max(a, b) for a, b in zip(max_shapes[k], shape))
opt_shapes: Dict[str, tuple] = {}
for k, v in counters.items():
opt_shapes[k] = v.most_common(1)[0][0]
shapes = {}
for k in opt_shapes.keys(): # same keys in min_shapes and max_shapes
shapes[k] = ShapeSpec(
min=(1,) + min_shapes[k][1:],
max=(max_batch_size,) + max_shapes[k][1:],
opt=(max_batch_size,) + opt_shapes[k][1:],
)
return shapes
|
TensorFlow2/Recommendation/WideAndDeep | WideAndDeep | hvd_wrapper | #!/bin/bash
# Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Get local process ID from OpenMPI or alternatively from SLURM
if [ -z "${CUDA_VISIBLE_DEVICES:-}" ]; then
if [ -n "${OMPI_COMM_WORLD_LOCAL_RANK:-}" ]; then
LOCAL_RANK="${OMPI_COMM_WORLD_LOCAL_RANK}"
elif [ -n "${SLURM_LOCALID:-}" ]; then
LOCAL_RANK="${SLURM_LOCALID}"
fi
export CUDA_VISIBLE_DEVICES=${LOCAL_RANK}
fi
exec "$@"
|
PyTorch/Detection/SSD/ssd | ssd | utils | # Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
import torchvision.transforms as transforms
import torch.utils.data as data
from PIL import Image
import os
import numpy as np
import random
import itertools
import torch.nn.functional as F
import json
import time
import bz2
import pickle
from math import sqrt
# This function is from https://github.com/kuangliu/pytorch-ssd.
def calc_iou_tensor(box1, box2):
""" Calculation of IoU based on two boxes tensor,
Reference to https://github.com/kuangliu/pytorch-src
input:
box1 (N, 4)
box2 (M, 4)
output:
IoU (N, M)
"""
N = box1.size(0)
M = box2.size(0)
be1 = box1.unsqueeze(1).expand(-1, M, -1)
be2 = box2.unsqueeze(0).expand(N, -1, -1)
# Left Top & Right Bottom
lt = torch.max(be1[:,:,:2], be2[:,:,:2])
#mask1 = (be1[:,:, 0] < be2[:,:, 0]) ^ (be1[:,:, 1] < be2[:,:, 1])
#mask1 = ~mask1
rb = torch.min(be1[:,:,2:], be2[:,:,2:])
#mask2 = (be1[:,:, 2] < be2[:,:, 2]) ^ (be1[:,:, 3] < be2[:,:, 3])
#mask2 = ~mask2
delta = rb - lt
delta[delta < 0] = 0
intersect = delta[:,:,0]*delta[:,:,1]
#*mask1.float()*mask2.float()
delta1 = be1[:,:,2:] - be1[:,:,:2]
area1 = delta1[:,:,0]*delta1[:,:,1]
delta2 = be2[:,:,2:] - be2[:,:,:2]
area2 = delta2[:,:,0]*delta2[:,:,1]
iou = intersect/(area1 + area2 - intersect)
return iou
# This function is from https://github.com/kuangliu/pytorch-ssd.
class Encoder(object):
"""
Inspired by https://github.com/kuangliu/pytorch-src
Transform between (bboxes, lables) <-> SSD output
dboxes: default boxes in size 8732 x 4,
encoder: input ltrb format, output xywh format
decoder: input xywh format, output ltrb format
encode:
input : bboxes_in (Tensor nboxes x 4), labels_in (Tensor nboxes)
output : bboxes_out (Tensor 8732 x 4), labels_out (Tensor 8732)
criteria : IoU threshold of bboexes
decode:
input : bboxes_in (Tensor 8732 x 4), scores_in (Tensor 8732 x nitems)
output : bboxes_out (Tensor nboxes x 4), labels_out (Tensor nboxes)
criteria : IoU threshold of bboexes
max_output : maximum number of output bboxes
"""
def __init__(self, dboxes):
self.dboxes = dboxes(order="ltrb")
self.dboxes_xywh = dboxes(order="xywh").unsqueeze(dim=0)
self.nboxes = self.dboxes.size(0)
self.scale_xy = dboxes.scale_xy
self.scale_wh = dboxes.scale_wh
def encode(self, bboxes_in, labels_in, criteria = 0.5):
ious = calc_iou_tensor(bboxes_in, self.dboxes)
best_dbox_ious, best_dbox_idx = ious.max(dim=0)
best_bbox_ious, best_bbox_idx = ious.max(dim=1)
# set best ious 2.0
best_dbox_ious.index_fill_(0, best_bbox_idx, 2.0)
idx = torch.arange(0, best_bbox_idx.size(0), dtype=torch.int64)
best_dbox_idx[best_bbox_idx[idx]] = idx
# filter IoU > 0.5
masks = best_dbox_ious > criteria
labels_out = torch.zeros(self.nboxes, dtype=torch.long)
labels_out[masks] = labels_in[best_dbox_idx[masks]]
bboxes_out = self.dboxes.clone()
bboxes_out[masks, :] = bboxes_in[best_dbox_idx[masks], :]
# Transform format to xywh format
x, y, w, h = 0.5*(bboxes_out[:, 0] + bboxes_out[:, 2]), \
0.5*(bboxes_out[:, 1] + bboxes_out[:, 3]), \
-bboxes_out[:, 0] + bboxes_out[:, 2], \
-bboxes_out[:, 1] + bboxes_out[:, 3]
bboxes_out[:, 0] = x
bboxes_out[:, 1] = y
bboxes_out[:, 2] = w
bboxes_out[:, 3] = h
return bboxes_out, labels_out
def scale_back_batch(self, bboxes_in, scores_in):
"""
Do scale and transform from xywh to ltrb
suppose input Nx4xnum_bbox Nxlabel_numxnum_bbox
"""
if bboxes_in.device == torch.device("cpu"):
self.dboxes = self.dboxes.cpu()
self.dboxes_xywh = self.dboxes_xywh.cpu()
else:
self.dboxes = self.dboxes.cuda()
self.dboxes_xywh = self.dboxes_xywh.cuda()
bboxes_in = bboxes_in.permute(0, 2, 1)
scores_in = scores_in.permute(0, 2, 1)
bboxes_in[:, :, :2] = self.scale_xy*bboxes_in[:, :, :2]
bboxes_in[:, :, 2:] = self.scale_wh*bboxes_in[:, :, 2:]
bboxes_in[:, :, :2] = bboxes_in[:, :, :2]*self.dboxes_xywh[:, :, 2:] + self.dboxes_xywh[:, :, :2]
bboxes_in[:, :, 2:] = bboxes_in[:, :, 2:].exp()*self.dboxes_xywh[:, :, 2:]
# Transform format to ltrb
l, t, r, b = bboxes_in[:, :, 0] - 0.5*bboxes_in[:, :, 2],\
bboxes_in[:, :, 1] - 0.5*bboxes_in[:, :, 3],\
bboxes_in[:, :, 0] + 0.5*bboxes_in[:, :, 2],\
bboxes_in[:, :, 1] + 0.5*bboxes_in[:, :, 3]
bboxes_in[:, :, 0] = l
bboxes_in[:, :, 1] = t
bboxes_in[:, :, 2] = r
bboxes_in[:, :, 3] = b
return bboxes_in, F.softmax(scores_in, dim=-1)
def decode_batch(self, bboxes_in, scores_in, criteria = 0.45, max_output=200):
bboxes, probs = self.scale_back_batch(bboxes_in, scores_in)
output = []
for bbox, prob in zip(bboxes.split(1, 0), probs.split(1, 0)):
bbox = bbox.squeeze(0)
prob = prob.squeeze(0)
output.append(self.decode_single(bbox, prob, criteria, max_output))
return output
# perform non-maximum suppression
def decode_single(self, bboxes_in, scores_in, criteria, max_output, max_num=200):
# Reference to https://github.com/amdegroot/ssd.pytorch
bboxes_out = []
scores_out = []
labels_out = []
for i, score in enumerate(scores_in.split(1, 1)):
# skip background
# print(score[score>0.90])
if i == 0: continue
# print(i)
score = score.squeeze(1)
mask = score > 0.05
bboxes, score = bboxes_in[mask, :], score[mask]
if score.size(0) == 0: continue
score_sorted, score_idx_sorted = score.sort(dim=0)
# select max_output indices
score_idx_sorted = score_idx_sorted[-max_num:]
candidates = []
#maxdata, maxloc = scores_in.sort()
while score_idx_sorted.numel() > 0:
idx = score_idx_sorted[-1].item()
bboxes_sorted = bboxes[score_idx_sorted, :]
bboxes_idx = bboxes[idx, :].unsqueeze(dim=0)
iou_sorted = calc_iou_tensor(bboxes_sorted, bboxes_idx).squeeze()
# we only need iou < criteria
score_idx_sorted = score_idx_sorted[iou_sorted < criteria]
candidates.append(idx)
bboxes_out.append(bboxes[candidates, :])
scores_out.append(score[candidates])
labels_out.extend([i]*len(candidates))
if not bboxes_out:
return [torch.tensor([]) for _ in range(3)]
bboxes_out, labels_out, scores_out = torch.cat(bboxes_out, dim=0), \
torch.tensor(labels_out, dtype=torch.long), \
torch.cat(scores_out, dim=0)
_, max_ids = scores_out.sort(dim=0)
max_ids = max_ids[-max_output:].to("cpu")
return bboxes_out[max_ids, :], labels_out[max_ids], scores_out[max_ids]
class DefaultBoxes(object):
def __init__(self, fig_size, feat_size, steps, scales, aspect_ratios, \
scale_xy=0.1, scale_wh=0.2):
self.feat_size = feat_size
self.fig_size = fig_size
self.scale_xy_ = scale_xy
self.scale_wh_ = scale_wh
# According to https://github.com/weiliu89/caffe
# Calculation method slightly different from paper
self.steps = steps
self.scales = scales
fk = fig_size/np.array(steps)
self.aspect_ratios = aspect_ratios
self.default_boxes = []
# size of feature and number of feature
for idx, sfeat in enumerate(self.feat_size):
sk1 = scales[idx]/fig_size
sk2 = scales[idx+1]/fig_size
sk3 = sqrt(sk1*sk2)
all_sizes = [(sk1, sk1), (sk3, sk3)]
for alpha in aspect_ratios[idx]:
w, h = sk1*sqrt(alpha), sk1/sqrt(alpha)
all_sizes.append((w, h))
all_sizes.append((h, w))
for w, h in all_sizes:
for i, j in itertools.product(range(sfeat), repeat=2):
cx, cy = (j+0.5)/fk[idx], (i+0.5)/fk[idx]
self.default_boxes.append((cx, cy, w, h))
self.dboxes = torch.tensor(self.default_boxes, dtype=torch.float)
self.dboxes.clamp_(min=0, max=1)
# For IoU calculation
self.dboxes_ltrb = self.dboxes.clone()
self.dboxes_ltrb[:, 0] = self.dboxes[:, 0] - 0.5 * self.dboxes[:, 2]
self.dboxes_ltrb[:, 1] = self.dboxes[:, 1] - 0.5 * self.dboxes[:, 3]
self.dboxes_ltrb[:, 2] = self.dboxes[:, 0] + 0.5 * self.dboxes[:, 2]
self.dboxes_ltrb[:, 3] = self.dboxes[:, 1] + 0.5 * self.dboxes[:, 3]
@property
def scale_xy(self):
return self.scale_xy_
@property
def scale_wh(self):
return self.scale_wh_
def __call__(self, order="ltrb"):
if order == "ltrb": return self.dboxes_ltrb
if order == "xywh": return self.dboxes
def dboxes300_coco():
figsize = 300
feat_size = [38, 19, 10, 5, 3, 1]
steps = [8, 16, 32, 64, 100, 300]
# use the scales here: https://github.com/amdegroot/ssd.pytorch/blob/master/data/config.py
scales = [21, 45, 99, 153, 207, 261, 315]
aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]
dboxes = DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
return dboxes
# This function is from https://github.com/chauhan-utk/ssd.DomainAdaptation.
class SSDCropping(object):
""" Cropping for SSD, according to original paper
Choose between following 3 conditions:
1. Preserve the original image
2. Random crop minimum IoU is among 0.1, 0.3, 0.5, 0.7, 0.9
3. Random crop
Reference to https://github.com/chauhan-utk/src.DomainAdaptation
"""
def __init__(self):
self.sample_options = (
# Do nothing
None,
# min IoU, max IoU
(0.1, None),
(0.3, None),
(0.5, None),
(0.7, None),
(0.9, None),
# no IoU requirements
(None, None),
)
def __call__(self, img, img_size, bboxes, labels):
# Ensure always return cropped image
while True:
mode = random.choice(self.sample_options)
if mode is None:
return img, img_size, bboxes, labels
htot, wtot = img_size
min_iou, max_iou = mode
min_iou = float("-inf") if min_iou is None else min_iou
max_iou = float("+inf") if max_iou is None else max_iou
# Implementation use 50 iteration to find possible candidate
for _ in range(1):
# suze of each sampled path in [0.1, 1] 0.3*0.3 approx. 0.1
w = random.uniform(0.3 , 1.0)
h = random.uniform(0.3 , 1.0)
if w/h < 0.5 or w/h > 2:
continue
# left 0 ~ wtot - w, top 0 ~ htot - h
left = random.uniform(0, 1.0 - w)
top = random.uniform(0, 1.0 - h)
right = left + w
bottom = top + h
ious = calc_iou_tensor(bboxes, torch.tensor([[left, top, right, bottom]]))
# tailor all the bboxes and return
if not ((ious > min_iou) & (ious < max_iou)).all():
continue
# discard any bboxes whose center not in the cropped image
xc = 0.5*(bboxes[:, 0] + bboxes[:, 2])
yc = 0.5*(bboxes[:, 1] + bboxes[:, 3])
masks = (xc > left) & (xc < right) & (yc > top) & (yc < bottom)
# if no such boxes, continue searching again
if not masks.any():
continue
bboxes[bboxes[:, 0] < left, 0] = left
bboxes[bboxes[:, 1] < top, 1] = top
bboxes[bboxes[:, 2] > right, 2] = right
bboxes[bboxes[:, 3] > bottom, 3] = bottom
bboxes = bboxes[masks, :]
labels = labels[masks]
left_idx = int(left*wtot)
top_idx = int(top*htot)
right_idx = int(right*wtot)
bottom_idx = int(bottom*htot)
img = img.crop((left_idx, top_idx, right_idx, bottom_idx))
bboxes[:, 0] = (bboxes[:, 0] - left)/w
bboxes[:, 1] = (bboxes[:, 1] - top)/h
bboxes[:, 2] = (bboxes[:, 2] - left)/w
bboxes[:, 3] = (bboxes[:, 3] - top)/h
htot = bottom_idx - top_idx
wtot = right_idx - left_idx
return img, (htot, wtot), bboxes, labels
class RandomHorizontalFlip(object):
def __init__(self, p=0.5):
self.p = p
def __call__(self, image, bboxes):
if random.random() < self.p:
bboxes[:, 0], bboxes[:, 2] = 1.0 - bboxes[:, 2], 1.0 - bboxes[:, 0]
return image.transpose(Image.FLIP_LEFT_RIGHT), bboxes
return image, bboxes
# Do data augumentation
class SSDTransformer(object):
""" SSD Data Augumentation, according to original paper
Composed by several steps:
Cropping
Resize
Flipping
Jittering
"""
def __init__(self, dboxes, size = (300, 300), val=False):
# define vgg16 mean
self.size = size
self.val = val
self.dboxes_ = dboxes #DefaultBoxes300()
self.encoder = Encoder(self.dboxes_)
self.crop = SSDCropping()
self.img_trans = transforms.Compose([
transforms.Resize(self.size),
transforms.ColorJitter(brightness=0.125, contrast=0.5,
saturation=0.5, hue=0.05
),
transforms.ToTensor()
])
self.hflip = RandomHorizontalFlip()
# All Pytorch Tensor will be normalized
# https://discuss.pytorch.org/t/how-to-preprocess-input-for-pre-trained-networks/683
self.normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225])
self.trans_val = transforms.Compose([
transforms.Resize(self.size),
transforms.ToTensor(),
#ToTensor(),
self.normalize,])
@property
def dboxes(self):
return self.dboxes_
def __call__(self, img, img_size, bbox=None, label=None, max_num=200):
#img = torch.tensor(img)
if self.val:
bbox_out = torch.zeros(max_num, 4)
label_out = torch.zeros(max_num, dtype=torch.long)
bbox_out[:bbox.size(0), :] = bbox
label_out[:label.size(0)] = label
return self.trans_val(img), img_size, bbox_out, label_out
img, img_size, bbox, label = self.crop(img, img_size, bbox, label)
img, bbox = self.hflip(img, bbox)
img = self.img_trans(img).contiguous()
img = self.normalize(img)
bbox, label = self.encoder.encode(bbox, label)
return img, img_size, bbox, label
# Implement a datareader for COCO dataset
class COCODetection(data.Dataset):
def __init__(self, img_folder, annotate_file, transform=None):
self.img_folder = img_folder
self.annotate_file = annotate_file
# Start processing annotation
with open(annotate_file) as fin:
self.data = json.load(fin)
self.images = {}
self.label_map = {}
self.label_info = {}
start_time = time.time()
# 0 stand for the background
cnt = 0
self.label_info[cnt] = "background"
for cat in self.data["categories"]:
cnt += 1
self.label_map[cat["id"]] = cnt
self.label_info[cnt] = cat["name"]
# build inference for images
for img in self.data["images"]:
img_id = img["id"]
img_name = img["file_name"]
img_size = (img["height"],img["width"])
if img_id in self.images: raise Exception("dulpicated image record")
self.images[img_id] = (img_name, img_size, [])
# read bboxes
for bboxes in self.data["annotations"]:
img_id = bboxes["image_id"]
category_id = bboxes["category_id"]
bbox = bboxes["bbox"]
bbox_label = self.label_map[bboxes["category_id"]]
self.images[img_id][2].append((bbox, bbox_label))
for k, v in list(self.images.items()):
if len(v[2]) == 0:
self.images.pop(k)
self.img_keys = list(self.images.keys())
self.transform = transform
@property
def labelnum(self):
return len(self.label_info)
@staticmethod
def load(pklfile):
with bz2.open(pklfile, "rb") as fin:
ret = pickle.load(fin)
return ret
def save(self, pklfile):
with bz2.open(pklfile, "wb") as fout:
pickle.dump(self, fout)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img_id = self.img_keys[idx]
img_data = self.images[img_id]
fn = img_data[0]
img_path = os.path.join(self.img_folder, fn)
img = Image.open(img_path).convert("RGB")
htot, wtot = img_data[1]
bbox_sizes = []
bbox_labels = []
#for (xc, yc, w, h), bbox_label in img_data[2]:
for (l,t,w,h), bbox_label in img_data[2]:
r = l + w
b = t + h
#l, t, r, b = xc - 0.5*w, yc - 0.5*h, xc + 0.5*w, yc + 0.5*h
bbox_size = (l/wtot, t/htot, r/wtot, b/htot)
bbox_sizes.append(bbox_size)
bbox_labels.append(bbox_label)
bbox_sizes = torch.tensor(bbox_sizes)
bbox_labels = torch.tensor(bbox_labels)
if self.transform != None:
img, (htot, wtot), bbox_sizes, bbox_labels = \
self.transform(img, (htot, wtot), bbox_sizes, bbox_labels)
else:
pass
return img, img_id, (htot, wtot), bbox_sizes, bbox_labels
def draw_patches(img, bboxes, labels, order="xywh", label_map={}):
import matplotlib.pyplot as plt
import matplotlib.patches as patches
# Suppose bboxes in fractional coordinate:
# cx, cy, w, h
# img = img.numpy()
img = np.array(img)
labels = np.array(labels)
bboxes = bboxes.numpy()
if label_map:
labels = [label_map.get(l) for l in labels]
if order == "ltrb":
xmin, ymin, xmax, ymax = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
cx, cy, w, h = (xmin + xmax)/2, (ymin + ymax)/2, xmax - xmin, ymax - ymin
else:
cx, cy, w, h = bboxes[:, 0], bboxes[:, 1], bboxes[:, 2], bboxes[:, 3]
htot, wtot,_ = img.shape
cx *= wtot
cy *= htot
w *= wtot
h *= htot
bboxes = zip(cx, cy, w, h)
plt.imshow(img)
ax = plt.gca()
for (cx, cy, w, h), label in zip(bboxes, labels):
if label == "background": continue
ax.add_patch(patches.Rectangle((cx-0.5*w, cy-0.5*h),
w, h, fill=False, color="r"))
bbox_props = dict(boxstyle="round", fc="y", ec="0.5", alpha=0.3)
ax.text(cx-0.5*w, cy-0.5*h, label, ha="center", va="center", size=15, bbox=bbox_props)
plt.show()
|
TensorFlow/Recommendation/WideAndDeep/trainer | trainer | __init__ | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
|
TensorFlow2/Recommendation/DLRM_and_DCNv2/nn | nn | dcn | # Copyright 2021 The TensorFlow Recommenders Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
#
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
"""Implements `Cross` Layer, the cross layer in Deep & Cross Network (DCN)."""
from typing import Union, Text, Optional
import tensorflow as tf
@tf.keras.utils.register_keras_serializable()
class Cross(tf.keras.layers.Layer):
"""Cross Layer in Deep & Cross Network to learn explicit feature interactions.
A layer that creates explicit and bounded-degree feature interactions
efficiently. The `call` method accepts `inputs` as a tuple of size 2
tensors. The first input `x0` is the base layer that contains the original
features (usually the embedding layer); the second input `xi` is the output
of the previous `Cross` layer in the stack, i.e., the i-th `Cross`
layer. For the first `Cross` layer in the stack, x0 = xi.
The output is x_{i+1} = x0 .* (W * xi + bias + diag_scale * xi) + xi,
where .* designates elementwise multiplication, W could be a full-rank
matrix, or a low-rank matrix U*V to reduce the computational cost, and
diag_scale increases the diagonal of W to improve training stability (
especially for the low-rank case).
References:
1. [R. Wang et al.](https://arxiv.org/pdf/2008.13535.pdf)
See Eq. (1) for full-rank and Eq. (2) for low-rank version.
2. [R. Wang et al.](https://arxiv.org/pdf/1708.05123.pdf)
Example:
```python
# after embedding layer in a functional model:
input = tf.keras.Input(shape=(None,), name='index', dtype=tf.int64)
x0 = tf.keras.layers.Embedding(input_dim=32, output_dim=6)
x1 = Cross()(x0, x0)
x2 = Cross()(x0, x1)
logits = tf.keras.layers.Dense(units=10)(x2)
model = tf.keras.Model(input, logits)
```
Args:
projection_dim: project dimension to reduce the computational cost.
Default is `None` such that a full (`input_dim` by `input_dim`) matrix
W is used. If enabled, a low-rank matrix W = U*V will be used, where U
is of size `input_dim` by `projection_dim` and V is of size
`projection_dim` by `input_dim`. `projection_dim` need to be smaller
than `input_dim`/2 to improve the model efficiency. In practice, we've
observed that `projection_dim` = d/4 consistently preserved the
accuracy of a full-rank version.
diag_scale: a non-negative float used to increase the diagonal of the
kernel W by `diag_scale`, that is, W + diag_scale * I, where I is an
identity matrix.
use_bias: whether to add a bias term for this layer. If set to False,
no bias term will be used.
kernel_initializer: Initializer to use on the kernel matrix.
bias_initializer: Initializer to use on the bias vector.
kernel_regularizer: Regularizer to use on the kernel matrix.
bias_regularizer: Regularizer to use on bias vector.
Input shape: A tuple of 2 (batch_size, `input_dim`) dimensional inputs.
Output shape: A single (batch_size, `input_dim`) dimensional output.
"""
def __init__(
self,
projection_dim: Optional[int] = None,
diag_scale: Optional[float] = 0.0,
use_bias: bool = True,
kernel_initializer: Union[
Text, tf.keras.initializers.Initializer] = "truncated_normal",
bias_initializer: Union[Text,
tf.keras.initializers.Initializer] = "zeros",
kernel_regularizer: Union[Text, None,
tf.keras.regularizers.Regularizer] = None,
bias_regularizer: Union[Text, None,
tf.keras.regularizers.Regularizer] = None,
**kwargs):
super(Cross, self).__init__(**kwargs)
self._projection_dim = projection_dim
self._diag_scale = diag_scale
self._use_bias = use_bias
self._kernel_initializer = tf.keras.initializers.get(kernel_initializer)
self._bias_initializer = tf.keras.initializers.get(bias_initializer)
self._kernel_regularizer = tf.keras.regularizers.get(kernel_regularizer)
self._bias_regularizer = tf.keras.regularizers.get(bias_regularizer)
self._input_dim = None
self._supports_masking = True
if self._diag_scale < 0:
raise ValueError(
"`diag_scale` should be non-negative. Got `diag_scale` = {}".format(
self._diag_scale))
def build(self, input_shape):
last_dim = input_shape[-1]
if self._projection_dim is None:
self._dense = tf.keras.layers.Dense(
last_dim,
kernel_initializer=self._kernel_initializer,
bias_initializer=self._bias_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
use_bias=self._use_bias,
)
else:
self._dense_u = tf.keras.layers.Dense(
self._projection_dim,
kernel_initializer=self._kernel_initializer,
kernel_regularizer=self._kernel_regularizer,
use_bias=False,
)
self._dense_v = tf.keras.layers.Dense(
last_dim,
kernel_initializer=self._kernel_initializer,
bias_initializer=self._bias_initializer,
kernel_regularizer=self._kernel_regularizer,
bias_regularizer=self._bias_regularizer,
use_bias=self._use_bias,
)
self.built = True
def call(self, x0: tf.Tensor, x: Optional[tf.Tensor] = None) -> tf.Tensor:
"""Computes the feature cross.
Args:
x0: The input tensor
x: Optional second input tensor. If provided, the layer will compute
crosses between x0 and x; if not provided, the layer will compute
crosses between x0 and itself.
Returns:
Tensor of crosses.
"""
if not self.built:
self.build(x0.shape)
if x is None:
x = x0
if x0.shape[-1] != x.shape[-1]:
raise ValueError(
"`x0` and `x` dimension mismatch! Got `x0` dimension {}, and x "
"dimension {}. This case is not supported yet.".format(
x0.shape[-1], x.shape[-1]))
if self._projection_dim is None:
prod_output = self._dense(x)
else:
prod_output = self._dense_v(self._dense_u(x))
if self._diag_scale:
prod_output = prod_output + self._diag_scale * x
return x0 * prod_output + x
def get_config(self):
config = {
"projection_dim":
self._projection_dim,
"diag_scale":
self._diag_scale,
"use_bias":
self._use_bias,
"kernel_initializer":
tf.keras.initializers.serialize(self._kernel_initializer),
"bias_initializer":
tf.keras.initializers.serialize(self._bias_initializer),
"kernel_regularizer":
tf.keras.regularizers.serialize(self._kernel_regularizer),
"bias_regularizer":
tf.keras.regularizers.serialize(self._bias_regularizer),
}
base_config = super(Cross, self).get_config()
return dict(list(base_config.items()) + list(config.items()))
class CrossNetwork(tf.Module):
def __init__(self, num_layers, projection_dim=None):
self.cross_layers = []
for _ in range(num_layers):
self.cross_layers.append(Cross(projection_dim=projection_dim))
def __call__(self, x0):
x = x0
for cl in self.cross_layers:
x = cl(x0=x0, x=x)
return x
|
TensorFlow2/LanguageModeling/ELECTRA | ELECTRA | optimization | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
# Copyright (c) 2020 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions and classes related to optimization (weight updates)."""
import re
import collections
import tensorflow as tf
import tensorflow_addons.optimizers as tfa_optimizers
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import state_ops
from tensorflow.python.training import training_ops
from utils import log
class WarmUp(tf.keras.optimizers.schedules.LearningRateSchedule):
"""Applys a warmup schedule on a given learning rate decay schedule."""
def __init__(self, initial_learning_rate, decay_schedule_fn, warmup_steps, power=1.0, name=None):
super().__init__()
self.initial_learning_rate = initial_learning_rate
self.warmup_steps = warmup_steps
self.power = power
self.decay_schedule_fn = decay_schedule_fn
self.name = name
def __call__(self, step):
with tf.name_scope(self.name or "WarmUp") as name:
# Implements polynomial warmup. i.e., if global_step < warmup_steps, the
# learning rate will be `global_step/num_warmup_steps * init_lr`.
global_step_float = tf.cast(step, tf.float32)
warmup_steps_float = tf.cast(self.warmup_steps, tf.float32)
warmup_percent_done = global_step_float / warmup_steps_float
warmup_learning_rate = self.initial_learning_rate * tf.math.pow(warmup_percent_done, self.power)
return tf.cond(
global_step_float < warmup_steps_float,
lambda: warmup_learning_rate,
lambda: self.decay_schedule_fn(step - self.warmup_steps),
name=name,
)
def get_config(self):
return {
"initial_learning_rate": self.initial_learning_rate,
"decay_schedule_fn": self.decay_schedule_fn,
"warmup_steps": self.warmup_steps,
"power": self.power,
"name": self.name,
}
def create_optimizer(init_lr, num_train_steps, num_warmup_steps, weight_decay_rate=0.01,
layerwise_lr_decay=-1, n_transformer_layers=None, clip_norm=1.0,
optimizer="adam", skip_adaptive=False, power=1.0, beta_1=0.9, beta_2=0.999, end_lr=0.0):
"""Creates an optimizer with learning rate schedule."""
# Implements linear decay of the learning rate.
learning_rate_fn = tf.keras.optimizers.schedules.PolynomialDecay(
initial_learning_rate=init_lr, decay_steps=num_train_steps - num_warmup_steps, end_learning_rate=end_lr, power=power
)
if num_warmup_steps:
learning_rate_fn = WarmUp(
initial_learning_rate=init_lr, decay_schedule_fn=learning_rate_fn, warmup_steps=num_warmup_steps
)
layer_decay = None
if layerwise_lr_decay > 0 and n_transformer_layers is not None:
layer_decay = _get_layer_decay(layerwise_lr_decay, n_transformer_layers)
if optimizer == "adam":
optimizer = AdamWeightDecay(
learning_rate=learning_rate_fn,
weight_decay_rate=weight_decay_rate,
layer_decay=layer_decay,
beta_1=beta_1,
beta_2=beta_2,
epsilon=1e-6,
exclude_from_weight_decay=["layer_norm", "bias", "LayerNorm"],
clip_norm=clip_norm,
)
else:
if skip_adaptive:
skip_list = ["layer_norm", "bias", "LayerNorm"]
else:
skip_list = ["None"]
log("Skip list for LAMB {}".format(skip_list))
optimizer = tfa_optimizers.LAMB(
learning_rate=learning_rate_fn,
weight_decay_rate=weight_decay_rate,
beta_1=beta_1,
beta_2=beta_2,
epsilon=1e-6,
exclude_from_weight_decay=["layer_norm", "bias", "LayerNorm"],
exclude_from_layer_adaptation=skip_list,
)
return optimizer
class AdamWeightDecay(tf.keras.optimizers.Adam):
"""Adam enables L2 weight decay and clip_by_global_norm on gradients.
Just adding the square of the weights to the loss function is *not* the
correct way of using L2 regularization/weight decay with Adam, since that will
interact with the m and v parameters in strange ways.
Instead we want ot decay the weights in a manner that doesn't interact with
the m/v parameters. This is equivalent to adding the square of the weights to
the loss with plain (non-momentum) SGD.
"""
def __init__(
self,
learning_rate=0.001,
beta_1=0.9,
beta_2=0.999,
epsilon=1e-7,
amsgrad=False,
weight_decay_rate=0.0,
include_in_weight_decay=None,
exclude_from_weight_decay=None,
layer_decay=None,
clip_norm=1.0,
name="AdamWeightDecay",
**kwargs
):
super().__init__(learning_rate, beta_1, beta_2, epsilon, amsgrad, name, **kwargs)
self.weight_decay_rate = weight_decay_rate
self._include_in_weight_decay = include_in_weight_decay
self._exclude_from_weight_decay = exclude_from_weight_decay
self.layer_decay = layer_decay
self.clip_norm = clip_norm
@classmethod
def from_config(cls, config):
"""Creates an optimizer from its config with WarmUp custom object."""
custom_objects = {"WarmUp": WarmUp}
return super().from_config(config, custom_objects=custom_objects)
def _prepare_local(self, var_device, var_dtype, apply_state):
super()._prepare_local(var_device, var_dtype, apply_state)
apply_state["weight_decay_rate"] = tf.constant(self.weight_decay_rate, name="adam_weight_decay_rate")
def _decay_weights_op(self, var, learning_rate, apply_state):
do_decay = self._do_use_weight_decay(var.name)
if do_decay:
return var.assign_sub(
learning_rate * var * apply_state["weight_decay_rate"], use_locking=self._use_locking
)
return tf.no_op()
def apply_gradients(self, grads_and_vars, name=None, experimental_aggregate_gradients=True):
grads, tvars = list(zip(*grads_and_vars))
# Being done in train_step
##(grads, _) = tf.clip_by_global_norm(grads, clip_norm=self.clip_norm)
return super().apply_gradients(zip(grads, tvars), name=name,
experimental_aggregate_gradients=experimental_aggregate_gradients)
def _get_lr(self, var, apply_state):
"""Retrieves the learning rate with the given state."""
# if apply_state is None:
# return self._decayed_lr_t[var_dtype], {}
var_name, var_device, var_dtype = var.name, var.device, var.dtype.base_dtype
apply_state = apply_state or {}
coefficients = apply_state.get((var_device, var_dtype))
if coefficients is None:
coefficients = self._fallback_apply_state(var_device, var_dtype)
apply_state[(var_device, var_dtype)] = coefficients
lr_t = coefficients["lr_t"]
lr = coefficients["lr"]
if self.layer_decay is not None:
update_for_var = False
for key in self.layer_decay:
if key in var_name:
update_for_var = True
lr_t *= self.layer_decay[key]
lr *= self.layer_decay[key]
break
if not update_for_var:
raise ValueError("No learning rate specified for variable", var)
return lr_t, lr, coefficients, dict(apply_state=apply_state)
def _resource_apply_dense(self, grad, var, apply_state=None):
# print("Dense: {} {} {}".format(var.name, var.device, var.dtype.base_dtype))
lr_t, _, coefficients, kwargs = self._get_lr(var, apply_state)
decay = self._decay_weights_op(var, lr_t, apply_state)
with tf.control_dependencies([decay]):
m = self.get_slot(var, 'm')
v = self.get_slot(var, 'v')
if not self.amsgrad:
return training_ops.resource_apply_adam(
var.handle,
m.handle,
v.handle,
coefficients['beta_1_power'],
coefficients['beta_2_power'],
lr_t,
coefficients['beta_1_t'],
coefficients['beta_2_t'],
coefficients['epsilon'],
grad,
use_locking=self._use_locking)
else:
vhat = self.get_slot(var, 'vhat')
return training_ops.resource_apply_adam_with_amsgrad(
var.handle,
m.handle,
v.handle,
vhat.handle,
coefficients['beta_1_power'],
coefficients['beta_2_power'],
lr_t,
coefficients['beta_1_t'],
coefficients['beta_2_t'],
coefficients['epsilon'],
grad,
use_locking=self._use_locking)
def _resource_apply_sparse(self, grad, var, indices, apply_state=None):
# print("Sparse: {} {} {}".format(var.name, var.device, var.dtype.base_dtype))
lr_t, lr, coefficients, kwargs = self._get_lr(var, apply_state)
decay = self._decay_weights_op(var, lr_t, apply_state)
with tf.control_dependencies([decay]):
# m_t = beta1 * m + (1 - beta1) * g_t
m = self.get_slot(var, 'm')
m_scaled_g_values = grad * coefficients['one_minus_beta_1_t']
m_t = state_ops.assign(m, m * coefficients['beta_1_t'],
use_locking=self._use_locking)
with tf.control_dependencies([m_t]):
m_t = self._resource_scatter_add(m, indices, m_scaled_g_values)
# v_t = beta2 * v + (1 - beta2) * (g_t * g_t)
v = self.get_slot(var, 'v')
v_scaled_g_values = (grad * grad) * coefficients['one_minus_beta_2_t']
v_t = state_ops.assign(v, v * coefficients['beta_2_t'],
use_locking=self._use_locking)
with tf.control_dependencies([v_t]):
v_t = self._resource_scatter_add(v, indices, v_scaled_g_values)
if not self.amsgrad:
v_sqrt = math_ops.sqrt(v_t)
var_update = state_ops.assign_sub(
var, lr * m_t / (v_sqrt + coefficients['epsilon']),
use_locking=self._use_locking)
return control_flow_ops.group(*[var_update, m_t, v_t])
else:
v_hat = self.get_slot(var, 'vhat')
v_hat_t = math_ops.maximum(v_hat, v_t)
with tf.control_dependencies([v_hat_t]):
v_hat_t = state_ops.assign(
v_hat, v_hat_t, use_locking=self._use_locking)
v_hat_sqrt = math_ops.sqrt(v_hat_t)
var_update = state_ops.assign_sub(
var,
lr * m_t / (v_hat_sqrt + coefficients['epsilon']),
use_locking=self._use_locking)
return control_flow_ops.group(*[var_update, m_t, v_t, v_hat_t])
def get_config(self):
config = super().get_config()
config.update({"weight_decay_rate": self.weight_decay_rate})
return config
def _do_use_weight_decay(self, param_name):
"""Whether to use L2 weight decay for `param_name`."""
if self.weight_decay_rate == 0:
return False
if self._include_in_weight_decay:
for r in self._include_in_weight_decay:
if re.search(r, param_name) is not None:
return True
if self._exclude_from_weight_decay:
for r in self._exclude_from_weight_decay:
if re.search(r, param_name) is not None:
return False
return True
# Inspired from https://github.com/OpenNMT/OpenNMT-tf/blob/master/opennmt/optimizers/utils.py
class GradientAccumulator(object):
"""Distribution strategies-aware gradient accumulation utility."""
def __init__(self):
"""Initializes the accumulator."""
self._gradients = []
self._accum_steps = tf.Variable(
initial_value=0, dtype=tf.int64, trainable=False, aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA
)
@property
def step(self):
"""Number of accumulated steps."""
return self._accum_steps.value()
@property
def gradients(self):
"""The accumulated gradients."""
return list(
gradient.value() if gradient is not None else gradient for gradient in self._get_replica_gradients()
)
def __call__(self, gradients):
"""Accumulates :obj:`gradients`."""
if not self._gradients:
self._gradients.extend(
[
tf.Variable(tf.zeros_like(gradient), trainable=False) if gradient is not None else gradient
for gradient in gradients
]
)
if len(gradients) != len(self._gradients):
raise ValueError("Expected %s gradients, but got %d" % (len(self._gradients), len(gradients)))
for accum_gradient, gradient in zip(self._get_replica_gradients(), gradients):
if accum_gradient is not None and gradient is not None:
accum_gradient.assign_add(gradient)
self._accum_steps.assign_add(1)
def reset(self):
"""Resets the accumulated gradients."""
if self._gradients:
self._accum_steps.assign(0)
for gradient in self._get_replica_gradients():
if gradient is not None:
gradient.assign(tf.zeros_like(gradient))
def _get_replica_gradients(self):
if tf.distribute.has_strategy():
# In a replica context, we want to accumulate gradients on each replica
# without synchronization, so we directly assign the value of the
# current replica.
replica_context = tf.distribute.get_replica_context()
if replica_context is None or tf.distribute.get_strategy().num_replicas_in_sync == 1:
return self._gradients
return (
gradient.device_map.select_for_current_replica(gradient.values, replica_context)
for gradient in self._gradients
if gradient is not None
)
else:
return self._gradients
def _get_layer_decay(layer_decay, n_layers):
"""Have lower learning rates for layers closer to the input."""
key_to_depths = collections.OrderedDict({
"/embeddings/": 0,
"/embeddings_project/": 0,
"/start_logits/": n_layers + 2,
"/end_logits/": n_layers + 2,
"/answer_class/": n_layers + 2,
"/qa_outputs/": n_layers + 2,
})
for layer in range(n_layers):
key_to_depths["encoder/layer_._" + str(layer) + "/"] = layer + 1
return {
key: layer_decay ** (n_layers + 2 - depth)
for key, depth in key_to_depths.items()
}
|
PyTorch/SpeechRecognition/wav2vec2/wav2vec2 | wav2vec2 | logging | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
from pathlib import Path
import dllogger
import torch.distributed as dist
from dllogger import StdOutBackend, JSONStreamBackend, Verbosity
from common import tb_dllogger
from common.metrics import MetricsAggregator
from common.tb_dllogger import (stdout_metric_format, stdout_step_format,
unique_log_fpath, TBLogger)
def init_logger(output_dir, log_file, ema_decay=0.0):
local_rank = 0 if not dist.is_initialized() else dist.get_rank()
if local_rank == 0:
Path(output_dir).mkdir(parents=False, exist_ok=True)
log_fpath = log_file or Path(output_dir, 'nvlog.json')
dllogger.init(backends=[
JSONStreamBackend(Verbosity.DEFAULT, log_fpath, append=True),
JSONStreamBackend(Verbosity.DEFAULT, unique_log_fpath(log_fpath)),
StdOutBackend(Verbosity.VERBOSE, step_format=stdout_step_format,
metric_format=stdout_metric_format)
])
init_train_metadata()
else:
dllogger.init(backends=[])
tb_train = ['train', 'train_avg']
tb_val = ['val']
tb_ema = [k + '_ema' for k in tb_val] if ema_decay > 0.0 else []
subset_names = {
'train': 'train_inner',
'train_avg': 'train',
'val': 'valid',
'val_ema': 'valid_ema',
}
enabled = (local_rank == 0)
tb_dllogger.tb_loggers = {
s: TBLogger(enabled, log_dir=output_dir, name=subset_names[s])
for s in tb_train + tb_val + tb_ema}
def init_train_metadata():
for id_, pref in [('train', ''), ('train_avg', 'avg train '),
('val', ' avg val '), ('val_ema', ' EMA val ')]:
dllogger.metadata(f"{id_}_loss",
{"name": f"{pref} loss", "format": ":>6.3f"})
dllogger.metadata(f"{id_}_accuracy",
{"name": f"{pref}acc", "format": ":>6.3f"})
dllogger.metadata(f"{id_}_prob_perplexity",
{"name": f"{pref}p pplx", "format": ":>6.3f"})
dllogger.metadata(f"{id_}_code_perplexity",
{"name": f"{pref}c pplx", "format": ":>6.3f"})
dllogger.metadata(f"{id_}_ntokens",
{"name": None, "unit": "tokens", "format": ":>8.0f"})
dllogger.metadata(f"{id_}_took",
{"name": "took", "unit": "s", "format": ":>3.2f"})
dllogger.metadata(f"{id_}_ntokens/s",
{"name": None, "unit": "tokens/s", "format": ":>8.2f"})
dllogger.metadata(f"{id_}_uer",
{"name": f"{pref} uer", "format": ":>6.2f"})
dllogger.metadata(f"{id_}_wer",
{"name": f"{pref} wer", "format": ":>6.2f"})
dllogger.metadata(f"{id_}_raw_wer",
{"name": f"{pref} raw wer", "format": ":>6.2f"})
dllogger.metadata(f"{id_}_lr",
{"name": "lr", "format": ":>3.2e"})
dllogger.metadata(f"{id_}_loss_scale",
{"name": "loss scale", "format": ":>3.2e"})
def init_infer_metadata():
for step in ['DNN', 'data+DNN', 'data']:
for c in [0.99, 0.95, 0.9, 0.5]:
cs = 'avg' if c == 0.5 else f'{int(100 * c)}%'
dllogger.metadata(f'{step.lower()}_latency_{c}',
{'name': f'{step} latency {cs}',
'format': ':>7.2f', 'unit': 'ms'})
dllogger.metadata(
'eval_wer', {'name': 'WER', 'format': ':>3.2f', 'unit': '%'})
class W2v2Metrics(MetricsAggregator):
def __init__(self, benchmark_epochs, scopes=('train', 'train_avg'), cuda=True):
super().__init__(
benchmark_epochs=benchmark_epochs,
benchmark_keys=('took', 'accuracy', 'loss', 'ntokens/s'),
scopes=scopes,
dllogger_keys=('loss', 'ntokens', 'accuracy', 'prob_perplexity',
'code_perplexity',
'took', 'loss_scale', 'lr', 'ntokens/s'),
reduce_mean=('temp', 'prob_perplexity', 'code_perplexity'),
reduce_last=('lr', 'loss_scale'),
cuda=cuda)
def accumulate(self, scopes=None):
if 'ignore' not in self.partials or self.partials['ignore'] == 0.0:
# compute_loss_and_accuracy
ntokens = self.partials['ntokens']
for k, v in self.partials.items():
if k.startswith('loss'):
self.partials[k] = v / ntokens / math.log(2) # as in fairseq
self['accuracy'] = (self.partials.pop('correct')
/ self.partials.pop('count'))
part_counts = self.partial_counts
assert part_counts['correct'] == part_counts['count'] == 1
super().accumulate(scopes=scopes)
def _finish_accumulating(self, scope='train'):
super()._finish_accumulating(scope=scope)
m = self.metrics[scope]
count = self.metric_counts[scope]
m['ntokens/s'] = m['ntokens'] * count['ntokens'] / m['took']
class W2v2FineTuningMetrics(MetricsAggregator):
def __init__(
self,
benchmark_epochs,
benchmark_keys=('took', 'accuracy', 'loss', 'ntokens/s'),
scopes=('train', 'train_avg'),
dllogger_keys=('loss', 'ntokens', 'accuracy', 'lr',
'prob_perplexity', 'took', 'ntokens/s', 'uer',
'wer', 'raw_wer'),
reduce_mean=('temp', 'prob_perplexity', 'code_perplexity'),
reduce_last=('lr',),
cuda=True):
super().__init__(
benchmark_epochs=benchmark_epochs, benchmark_keys=benchmark_keys,
scopes=scopes, dllogger_keys=dllogger_keys,
reduce_mean=reduce_mean, reduce_last=reduce_last, cuda=cuda)
def accumulate(self, scopes=None):
if 'ignore' not in self.partials or self.partials['ignore'] == 0.0:
# compute_loss_and_accuracy
nsentences = self.partials['nsentences']
for k, v in self.partials.items():
if k.startswith('loss'):
self.partials[k] = v / nsentences / math.log(2) # as in fairseq
super().accumulate(scopes=scopes)
def _finish_accumulating(self, scope='train'):
super()._finish_accumulating(scope=scope)
m = self.metrics[scope]
count = self.metric_counts[scope]
m['ntokens/s'] = m['ntokens'] * count['ntokens'] / m['took']
if 'c_errs' in m:
m['uer'] = 100 * m['c_errs'] / m['c_len']
if 'w_errs' in m:
m['wer'] = 100 * m['w_errs'] / m['w_len']
if 'wv_errs' in m:
m['raw_wer'] = 100 * m['wv_errs'] / m['w_len']
|
Tools/DGLPyTorch/SyntheticGraphGeneration/demos/basic_examples | basic_examples | e2e_cora_demo | #!/usr/bin/env python
# coding: utf-8
# Copyright 2023 NVIDIA Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# # End to end graph generation demo (CORA)
# ## Overview
#
# In this notebook, we have walked through the complete process of generating a synthetic dataset based on a CORA dataset. The CORA dataset consists of scientific publications classified into one of seven classes. Each publication in the dataset is described by a 0/1-valued word vector indicating the absence/presence of the corresponding word from the dictionary, so we can interpret the CORA dataset as a graph with categorical node features.
#
# Content:
#
# 1. [Prepare the original dataset](#1)
# 1. [Preprare SynGen Configuration](#2)
# 1. [Dataset Generation](#3)
# 1. [Tabular data evaluation](#4)
# 1. [Structure evaluation](#5)
# ### Imports
# In[1]:
# preprocessing
from syngen.preprocessing.datasets import CORAPreprocessing
# config
from syngen.configuration import SynGenConfiguration
# generation
from syngen.synthesizer import ConfigurationGraphSynthesizer
# evaluation
from syngen.analyzer.tabular import TabularMetrics
from syngen.analyzer.graph import Graph
from syngen.analyzer.graph.stats import get_dd_simmilarity_score
from syngen.analyzer.graph.analyser import AnalysisModule
# utils
import copy
from syngen.utils.types import MetaData
# <a id="1"></a>
# ## Prepare original dataset
# SynGen requires the data to be in SynGen dataset format or simply SynGen format, so firstly, we transform the raw Cora dataset into SynGen format. If you don't download Cora before, you may pass `download=True` as `CoraPreprocessing` class supports automatic downloading.
# In[2]:
data_path = '/workspace/data/cora'
preprocessed_path = '/workspace/data/cora_preprocessed'
# In[3]:
preprocessing = CORAPreprocessing(source_path=data_path, destination_path=preprocessed_path, download=False)
# In[4]:
feature_spec_original = preprocessing.transform(use_cache=True)
# In[5]:
feature_spec_original
# <a id="2"></a>
# ## Preprare SynGen Configuration
# SynGen generation process is driven by the configuration that is the superset of the SynGen format metadata file. Let us create two configurations: a proper one that will mimic Cora dataset tabular and structural features and a random one.
# ### Proper Synthetic
# In[6]:
feature_spec_synthetic = feature_spec_original.copy()
feature_spec_synthetic[MetaData.NODES][0][MetaData.TABULAR_GENERATORS] = [
{
MetaData.TYPE: "kde",
MetaData.FEATURES_LIST: -1, # copies all tabular features
MetaData.DATA_SOURCE: {
MetaData.TYPE: 'configuration',
MetaData.PATH: preprocessed_path,
MetaData.NAME: "paper",
},
MetaData.PARAMS: {
}
}
]
feature_spec_synthetic[MetaData.EDGES][0][MetaData.STRUCTURE_GENERATOR] = {
MetaData.TYPE: "RMAT",
MetaData.DATA_SOURCE: {
MetaData.TYPE: 'cfg', # the same a 'configuration'
MetaData.PATH: preprocessed_path,
MetaData.NAME: "cite",
},
MetaData.PARAMS: {
"has_self_loop": False,
}
}
# aligns 'label' node feature based on the 'cite' edges
feature_spec_synthetic[MetaData.ALIGNERS] = [
{
MetaData.TYPE: "xgboost",
MetaData.GRAPHS: ['cite'],
MetaData.NODES: {"paper": ["label"]},
MetaData.EDGES: {},
MetaData.PARAMS: {},
}
]
config_proper = SynGenConfiguration(feature_spec_synthetic)
# In[7]:
config_proper
# ### Random
# In[8]:
feature_spec_random = feature_spec_original.copy()
feature_spec_random[MetaData.NODES][0][MetaData.TABULAR_GENERATORS] = [
{
MetaData.TYPE: "random",
MetaData.FEATURES_LIST: -1, # copies all tabular features
MetaData.DATA_SOURCE: {
MetaData.TYPE: 'random',
},
MetaData.PARAMS: {
}
}
]
feature_spec_random[MetaData.EDGES][0][MetaData.STRUCTURE_GENERATOR] = {
MetaData.TYPE: "RMAT",
MetaData.DATA_SOURCE: {
MetaData.TYPE: 'rnd', # the save as 'random'
},
MetaData.PARAMS: {
"has_self_loop": False,
}
}
config_random = SynGenConfiguration(feature_spec_random)
# In[9]:
config_random
# <a id="3"></a>
# ## Dataset Generation
# In[10]:
save_path_proper = '/workspace/data/cora_generated'
save_path_random = '/workspace/data/cora_random'
# ### Create Synthesizers
# In[11]:
synthesizer_proper = ConfigurationGraphSynthesizer(configuration=config_proper, save_path=save_path_proper, gpu=True)
synthesizer_random = ConfigurationGraphSynthesizer(configuration=config_random, save_path=save_path_random, gpu=True)
# ### Fit Synthesizers
# In[12]:
synthesizer_proper.fit()
# In[13]:
synthesizer_random.fit()
# ### Generation
# In[14]:
feature_spec_generated_proper = synthesizer_proper.generate()
# In[15]:
feature_spec_generated_proper
# In[16]:
feature_spec_generated_random = synthesizer_random.generate()
# In[17]:
feature_spec_generated_random
# <a id="4"></a>
# ## Tabular Data Evaluation
# In[18]:
original_tabular_data, categorical_features = feature_spec_original.get_tabular_data(MetaData.NODES, 'paper', return_cat_feats=True)
# In[19]:
proper_tabular_data = feature_spec_generated_proper.get_tabular_data(MetaData.NODES, 'paper')
# In[20]:
random_tabular_data = feature_spec_generated_random.get_tabular_data(MetaData.NODES, 'paper')
# In[21]:
tab_eval = TabularMetrics(original_tabular_data,
proper_tabular_data,
categorical_columns=categorical_features)
# In[22]:
tab_eval.plot_pca()
# In[23]:
tab_eval = TabularMetrics(original_tabular_data,
random_tabular_data,
categorical_columns=categorical_features)
# In[24]:
tab_eval.plot_pca()
# <a id="5"></a>
# ## Structute Evaluation
# In[25]:
original_graph_structure = feature_spec_original.get_structural_data('cite')
proper_graph_structure = feature_spec_generated_proper.get_structural_data('cite')
random_graph_structure = feature_spec_generated_random.get_structural_data('cite')
# In[26]:
orig_proper = get_dd_simmilarity_score(original_graph_structure, proper_graph_structure, cdf_points=1000)
orig_random = get_dd_simmilarity_score(original_graph_structure, random_graph_structure, cdf_points=1000)
print("DEGREE SIMILLARITY SCORE")
print("ORIG vs PROPER:", orig_proper)
print("ORIG vs RANDOM:", orig_random)
# In[27]:
original_snap_graph = Graph.instantiate_from_feature_spec(feature_spec_original, 'cite', graph_name='original')
proper_snap_graph = Graph.instantiate_from_feature_spec(feature_spec_generated_proper, 'cite', graph_name='properly_generated')
random_graph_structure = Graph.instantiate_from_feature_spec(feature_spec_generated_random, 'cite', graph_name='randomly_generated')
all_graphs = [original_snap_graph, proper_snap_graph, random_graph_structure]
# In[28]:
graph_analyser = AnalysisModule()
# In[29]:
df = graph_analyser.compare_graph_stats(*all_graphs)
df
# In[30]:
from matplotlib.pyplot import set_loglevel
set_loglevel('warning')
_ = graph_analyser.compare_graph_plots(*all_graphs)
# In[ ]:
|
PyTorch/Classification/GPUNet/triton/deployment_toolkit/triton_performance_runner/model_analyzer | model_analyzer | model_analyzer_config | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .exceptions import ModelAnalyzerException
class ModelAnalyzerConfig:
"""
A config class to set arguments to the Model Analyzer.
An argument set to None will use the default.
"""
model_analyzer_args = [
"config-file",
]
input_to_options = [
"config-file",
]
def __init__(self):
# Args will be a dict with the string representation as key
self._args = {k: None for k in self.model_analyzer_args}
self._options = {
"-f": "config.yaml",
}
self._input_to_options = {
"config-file": "-f",
}
def to_cli_string(self):
"""
Utility function to convert a config into a
string of arguments to the server with CLI.
Returns
-------
str
the command consisting of all set arguments to
the model analyzer.
e.g. '--model-repository=/models --verbose=True'
"""
# single dashed options, then verbose flags, then main args
args = [f"{k} {v}" for k, v in self._options.items() if v]
args += [f"--{k}={v}" for k, v in self._args.items() if v]
return " ".join(args)
@classmethod
def allowed_keys(cls):
"""
Returns
-------
list of str
The keys that are allowed to be
passed into model_analyzer
"""
return list(cls.model_analyzer_args) + list(cls.input_to_options)
def __getitem__(self, key):
"""
Gets an arguments value in config
Parameters
----------
key : str
The name of the argument to the model analyzer
Returns
-------
The value that the argument is set to in this config
"""
if key in self._args:
return self._args[key]
elif key in self._input_to_options:
return self._options[self._input_to_options[key]]
else:
raise ModelAnalyzerException(f"'{key}' Key not found in config")
def __setitem__(self, key, value):
"""
Sets an arguments value in config
after checking if defined/supported.
Parameters
----------
key : str
The name of the argument to the model analyzer
value : (any)
The value to which the argument is being set
Raises
------
TritonModelAnalyzerException
If key is unsupported or undefined in the
config class
"""
if key in self._args:
self._args[key] = value
elif key in self._input_to_options:
self._options[self._input_to_options[key]] = value
else:
raise ModelAnalyzerException(f"The argument '{key}' to the Model Analyzer is not supported.")
|
PyTorch/LanguageModeling/BERT | BERT | schedulers | # Copyright (c) 2019-2021 NVIDIA CORPORATION. All rights reserved.
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import math
import torch
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import _LRScheduler
class LRScheduler(_LRScheduler):
def __init__(self, optimizer, last_epoch=-1):
# Check if using mixed precision training
self.mixed_training = False
base_optimizer = optimizer
# Check that optimizer param is valid
if not isinstance(optimizer, Optimizer):
raise TypeError('{} is not an Optimizer'.format(
type(optimizer).__name__))
super(LRScheduler, self).__init__(base_optimizer, last_epoch)
def step(self, epoch=None):
# Set the current training step
# ('epoch' is used to be consistent with _LRScheduler)
if self.mixed_training:
# The assumption is that the step will be constant
state_dict = self.optimizer.state[self.optimizer.param_groups[0]['params'][0]]
if 'step' in state_dict:
self.last_epoch = state_dict['step'] + 1
else:
self.last_epoch = 1
else:
self.last_epoch = epoch if epoch is not None else self.last_epoch + 1
for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):
param_group['lr'] = lr
class ConstantLR(LRScheduler):
def get_lr(self):
return self.base_lrs
class CosineWarmUpScheduler(LRScheduler):
"""
Applies a warm up period to the learning rate.
"""
def __init__(self, optimizer, warmup, total_steps, last_epoch=-1):
self.warmup = warmup
self.total_steps = total_steps
super(CosineWarmUpScheduler, self).__init__(optimizer, last_epoch)
def get_lr(self):
progress = self.last_epoch / self.total_steps
if progress < self.warmup:
return [base_lr * progress / self.warmup for base_lr in self.base_lrs]
else:
return [base_lr * (0.5 * (1.0 + torch.cos(math.pi + progress))) for base_lr in self.base_lrs]
class ConstantWarmUpScheduler(LRScheduler):
"""
Applies a warm up period to the learning rate.
"""
def __init__(self, optimizer, warmup, total_steps, last_epoch=-1):
self.warmup = warmup
self.total_steps = total_steps
super(ConstantWarmUpScheduler, self).__init__(optimizer, last_epoch)
def get_lr(self):
progress = self.last_epoch / self.total_steps
if progress < self.warmup:
return [base_lr * progress / self.warmup for base_lr in self.base_lrs]
else:
return self.base_lrs
class LinearWarmUpScheduler(LRScheduler):
"""
Applies a warm up period to the learning rate.
"""
def __init__(self, optimizer, warmup, total_steps, last_epoch=-1):
self.warmup = warmup
self.total_steps = total_steps
super(LinearWarmUpScheduler, self).__init__(optimizer, last_epoch)
def get_lr(self):
progress = self.last_epoch / self.total_steps
if progress < self.warmup:
return [base_lr * progress / self.warmup for base_lr in self.base_lrs]
else:
return [base_lr * max(( progress - 1.0)/(self.warmup - 1.0), 0.) for base_lr in self.base_lrs]
class PolyWarmUpScheduler(LRScheduler):
"""
Applies a warm up period to the learning rate.
"""
def __init__(self, optimizer, warmup, total_steps, degree=0.5, last_epoch=-1, base_lr=1., device='cpu'):
self.warmup = torch.tensor(warmup, device=device)
self.total_steps = torch.tensor(total_steps, device=device)
self.degree = torch.tensor(degree, device=device)
device_last_epoch = torch.tensor(last_epoch, device=device)
self.base_lr = torch.tensor(base_lr, device=device)
self.device = device
super(PolyWarmUpScheduler, self).__init__(optimizer, device_last_epoch)
def step(self, epoch=None):
param_group = self.optimizer.param_groups[0]
if 'step' in param_group:
self.last_epoch = param_group['step'] + 1
else:
self.last_epoch = torch.tensor(1., device=self.device)
for param_group, lr in zip(self.optimizer.param_groups, self.get_lr()):
param_group['lr'] = lr
def get_lr(self):
progress = self.last_epoch / self.total_steps
lr_tensor = torch.where(progress < self.warmup, self.base_lr * progress / self.warmup, self.base_lr * ((1.0 - progress) ** self.degree))
return [lr_tensor for _ in range(len(self.optimizer.param_groups))]
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt/tacotron2 | tacotron2 | decoderInstance | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TT2I_DECODERINSTANCE_H
#define TT2I_DECODERINSTANCE_H
#include "binding.h"
#include "dropoutGenerator.h"
#include "engineCache.h"
#include "engineDriver.h"
#include "hostMemory.h"
#include "timedObject.h"
#include "trtPtr.h"
#include "NvInfer.h"
#include <cuda_runtime.h>
#include <curand.h>
#include <curand_kernel.h>
#include <memory>
#include <string>
namespace tts
{
class DecoderInstance : public TimedObject, public EngineDriver
{
public:
static constexpr const char* const INPUT_MASK_NAME = "input_decoder_mask";
static constexpr const char* const INPUT_LENGTH_NAME = "input_decoder_length";
static constexpr const char* const INPUT_DROPOUT_NAME = "input_decoder_dropout";
static constexpr const char* const INPUT_LASTFRAME_NAME = "input_decoder_lastframe";
static constexpr const char* const INPUT_MEMORY_NAME = "input_attention_memory";
static constexpr const char* const INPUT_PROCESSED_NAME = "input_attention_processed";
static constexpr const char* const INPUT_WEIGHTS_NAME = "input_attention_weights";
static constexpr const char* const INPUT_CONTEXT_NAME = "input_attentionlstm_contextinput";
static constexpr const char* const INPUT_ATTENTIONHIDDEN_NAME = "input_attentionlstm_hidden";
static constexpr const char* const INPUT_ATTENTIONCELL_NAME = "input_attentionlstm_cell";
static constexpr const char* const INPUT_DECODERHIDDEN_NAME = "input_decoderlstm_hidden";
static constexpr const char* const INPUT_DECODERCELL_NAME = "input_decoderlstm_cell";
static constexpr const char* const OUTPUT_ATTENTIONHIDDEN_NAME = "output_attentionlstm_hidden";
static constexpr const char* const OUTPUT_ATTENTIONCELL_NAME = "output_attentionlstm_cell";
static constexpr const char* const OUTPUT_CONTEXT_NAME = "output_attention_context";
static constexpr const char* const OUTPUT_WEIGHTS_NAME = "output_attention_weight";
static constexpr const char* const OUTPUT_DECODERHIDDEN_NAME = "output_decoderlstm_hidden";
static constexpr const char* const OUTPUT_DECODERCELL_NAME = "output_decoderlstm_cell";
static constexpr const char* const OUTPUT_CHANNELS_NAME = "output_projection_channels";
static constexpr const char* const OUTPUT_GATE_NAME = "output_projection_gates";
/**
* @brief Create a new DecoderInstance.
*
* @param engine The ICudaEngine containing the decoder network.
* @param maxChunkSize The maximum sized chunk the decoder will process.
*/
DecoderInstance(TRTPtr<nvinfer1::ICudaEngine> engine, int maxChunkSize);
/**
* @brief Do inference.
*
* @param stream The cuda stream.
* @param batchSize The size of the batch to perform inference on.
* @param inputDevice The input tensor on the device (memory).
* @param inputProcessedDevice The processed input tensor (memory_procssed).
* @param inputMaskDevice The mask of the input.
* @param inputLengthHost The length of the input on the host for eeach
* sequence.
* @param inputLengthDevice The length of the input in a 1x1 tensor
* (e.g., [[inputLength]]).
* @param outputDevice The output tensor on the device.
*/
virtual void infer(cudaStream_t stream, int batchSize, const float* inputDevice, const float* inputProcessedDevice,
const float* inputMaskDevice, const int32_t* inputLengthHost, const int32_t* inputLengthDevice,
float* outputDevice);
/**
* @brief Get the size of the last chunk processed.
*
* @return The size of the last chunk processed for each item in the batch.
*/
const int* lastChunkSize() const;
/**
* @brief Check if the decoder has finished processing the whole batch.
*
* @return True if decoding has finished.
*/
bool isAllDone() const;
/**
* @brief Reset the decoder for new input.
*
* @param stream The stream to run on.
*/
virtual void reset(cudaStream_t stream);
/**
* @brief Set the number of decoder loops to execute for subsequent calls to
* infer. The number must be less than or equal to the return of
* `getMaxChunkSize()`. By default this is equal to `getMaxChunkSize()`,
* and upon calls to `reset()` it returns to that value.
*
* @param chunkSize The number of frames to generate.
*/
void setNextChunkSize(int chunkSize);
/**
* @brief The random seed to use for dropouts.
*
* @param seed The seed value.
*/
void setSeed(unsigned int seed);
/**
* @brief Get maximum size of the next chunk of mel spectrograms frames to be
* generated.
*
* @return The number of frames that will be generated.
*/
int getNextChunkSize() const;
/**
* @brief Get the maximum chunk size that can be generated.
*
* @return The maximum chunk size in frames.
*/
int getMaxChunkSize() const;
/**
* @brief Get the dropout values used for inference. Must have called
* `setSaveDropouts()` to true before calling this method.
*
* @return The dropout values.
*/
std::vector<float> getDropoutRecord() const;
protected:
/**
* @brief Decode a single frame of output.
*
* @param stream The stream to operate on.
* @param context The execution context.
* @param batchSize The size of the batch to process.
* @param inputLastFrameDevice The last frame of output produced (all 0s
* for first frame).
* @param inputMemoryDevice The "Memory" tensor on the device.
* @param inputProcessedMemoryDevice The "Processed Memory" tensor on the
* device.
* @param inputMaskDevice The input mask on the device (1 for i < input
* length, 0 for i >= input length).
* @param inputLengthHost The length of each input item on the host.
* @param inputLengthDevice The length of each input on the device.
* @param inputDropoutsDevice The dropout vector to use on the device.
* @param outputFrameDevice The output frame on the device.
*/
virtual void decode(cudaStream_t stream, nvinfer1::IExecutionContext& context, int batchSize,
const float* inputLastFrameDevice, const float* inputMemoryDevice, const float* inputProcessedMemoryDevice,
const float* inputMaskDevice, const int32_t* inputLengthHost, const int32_t* inputLengthDevice,
const float* inputDropoutsDevice, float* outputFrameDevice)
= 0;
private:
TRTPtr<nvinfer1::IExecutionContext> mContext;
int mMaxChunkSize;
int mNextChunkSize;
int mNumChannels;
float mStopThreshold;
int mBatchSize;
unsigned int mSeed;
std::vector<int> mLastChunkSize;
std::vector<int> mDone;
DropoutGenerator mDropout;
CudaMemory<float> mDecoderInputDevice;
CudaMemory<float> mGateOutputDevice;
CudaMemory<float> mOutputTransposedDevice;
HostMemory<float> mOutputGateHost;
};
} // namespace tts
#endif
|
PyTorch/SpeechSynthesis/HiFiGAN/platform | platform | DGXA100_HiFi-GAN_AMP_4GPU | #!/bin/bash
set -a
: ${NUM_GPUS:=4}
: ${BATCH_SIZE:=32}
: ${GRAD_ACCUMULATION:=1}
: ${AMP:=true}
bash scripts/train_lj22khz.sh "$@" --no_amp_grouped_conv
|
CUDA-Optimized/FastSpeech/tacotron2 | tacotron2 | plotting_utils | # BSD 3-Clause License
# Copyright (c) 2018-2020, NVIDIA Corporation
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""https://github.com/NVIDIA/tacotron2"""
import matplotlib
matplotlib.use("Agg")
import matplotlib.pylab as plt
import numpy as np
def save_figure_to_numpy(fig):
# save it to a numpy array.
data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,))
return data
def plot_alignment_to_numpy(alignment, info=None):
fig, ax = plt.subplots(figsize=(6, 4))
im = ax.imshow(alignment, aspect='auto', origin='lower',
interpolation='none')
fig.colorbar(im, ax=ax)
xlabel = 'Decoder timestep'
if info is not None:
xlabel += '\n\n' + info
plt.xlabel(xlabel)
plt.ylabel('Encoder timestep')
plt.tight_layout()
fig.canvas.draw()
data = save_figure_to_numpy(fig)
plt.close()
return data
def plot_spectrogram_to_numpy(spectrogram):
fig, ax = plt.subplots(figsize=(12, 3))
im = ax.imshow(spectrogram, aspect="auto", origin="lower",
interpolation='none')
plt.colorbar(im, ax=ax)
plt.xlabel("Frames")
plt.ylabel("Channels")
plt.tight_layout()
fig.canvas.draw()
data = save_figure_to_numpy(fig)
plt.close()
return data
def plot_gate_outputs_to_numpy(gate_targets, gate_outputs):
fig, ax = plt.subplots(figsize=(12, 3))
ax.scatter(range(len(gate_targets)), gate_targets, alpha=0.5,
color='green', marker='+', s=1, label='target')
ax.scatter(range(len(gate_outputs)), gate_outputs, alpha=0.5,
color='red', marker='.', s=1, label='predicted')
plt.xlabel("Frames (Green target, Red predicted)")
plt.ylabel("Gate State")
plt.tight_layout()
fig.canvas.draw()
data = save_figure_to_numpy(fig)
plt.close()
return data
|
TensorFlow2/Segmentation/UNet_Medical/examples | examples | unet_TRAIN_SINGLE_TF-AMP | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# This script launches U-Net run in TF-AMP and trains for 6400 iterations with batch_size 8. Usage:
# bash unet_TRAIN_SINGLE.sh <number of gpus> <path to dataset> <path to results directory>
horovodrun -np $1 python main.py --data_dir $2 --model_dir $3 --log_every 100 --max_steps 6400 --batch_size 8 --exec_mode train_and_evaluate --fold 0 --augment --xla --amp --log_dir $3/log.json |
PyTorch/Segmentation/MaskRCNN/pytorch/configs | configs | e2e_mask_rcnn_R_50_FPN_1x_1GPU | MODEL:
META_ARCHITECTURE: "GeneralizedRCNN"
WEIGHT: "catalog://ImageNetPretrained/MSRA/R-50"
BACKBONE:
CONV_BODY: "R-50-FPN"
OUT_CHANNELS: 256
RPN:
USE_FPN: True
ANCHOR_STRIDE: (4, 8, 16, 32, 64)
PRE_NMS_TOP_N_TRAIN: 2000
PRE_NMS_TOP_N_TEST: 1000
POST_NMS_TOP_N_TEST: 1000
FPN_POST_NMS_TOP_N_TEST: 1000
ROI_HEADS:
USE_FPN: True
ROI_BOX_HEAD:
POOLER_RESOLUTION: 7
POOLER_SCALES: (0.25, 0.125, 0.0625, 0.03125)
POOLER_SAMPLING_RATIO: 2
FEATURE_EXTRACTOR: "FPN2MLPFeatureExtractor"
PREDICTOR: "FPNPredictor"
ROI_MASK_HEAD:
POOLER_SCALES: (0.25, 0.125, 0.0625, 0.03125)
FEATURE_EXTRACTOR: "MaskRCNNFPNFeatureExtractor"
PREDICTOR: "MaskRCNNC4Predictor"
POOLER_RESOLUTION: 14
POOLER_SAMPLING_RATIO: 2
RESOLUTION: 28
SHARE_BOX_FEATURE_EXTRACTOR: False
MASK_ON: True
DATASETS:
TRAIN: ("coco_2014_train", "coco_2014_valminusminival")
TEST: ("coco_2014_minival",)
DATALOADER:
SIZE_DIVISIBILITY: 32
SOLVER:
BASE_LR: 0.005
WEIGHT_DECAY: 0.0001
STEPS: (240000, 360000)
MAX_ITER: 360000
IMS_PER_BATCH: 4
TEST:
IMS_PER_BATCH: 1 |
TensorFlow/Detection/SSD/models/research/object_detection/utils | utils | per_image_vrd_evaluation_test | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for object_detection.utils.per_image_vrd_evaluation."""
import numpy as np
import tensorflow as tf
from object_detection.utils import per_image_vrd_evaluation
class SingleClassPerImageVrdEvaluationTest(tf.test.TestCase):
def setUp(self):
matching_iou_threshold = 0.5
self.eval = per_image_vrd_evaluation.PerImageVRDEvaluation(
matching_iou_threshold)
box_data_type = np.dtype([('subject', 'f4', (4,)), ('object', 'f4', (4,))])
self.detected_box_tuples = np.array(
[([0, 0, 1.1, 1], [1, 1, 2, 2]), ([0, 0, 1, 1], [1, 1, 2, 2]),
([1, 1, 2, 2], [0, 0, 1.1, 1])],
dtype=box_data_type)
self.detected_scores = np.array([0.8, 0.2, 0.1], dtype=float)
self.groundtruth_box_tuples = np.array(
[([0, 0, 1, 1], [1, 1, 2, 2])], dtype=box_data_type)
def test_tp_fp_eval(self):
tp_fp_labels = self.eval._compute_tp_fp_for_single_class(
self.detected_box_tuples, self.groundtruth_box_tuples)
expected_tp_fp_labels = np.array([True, False, False], dtype=bool)
self.assertTrue(np.allclose(expected_tp_fp_labels, tp_fp_labels))
def test_tp_fp_eval_empty_gt(self):
box_data_type = np.dtype([('subject', 'f4', (4,)), ('object', 'f4', (4,))])
tp_fp_labels = self.eval._compute_tp_fp_for_single_class(
self.detected_box_tuples, np.array([], dtype=box_data_type))
expected_tp_fp_labels = np.array([False, False, False], dtype=bool)
self.assertTrue(np.allclose(expected_tp_fp_labels, tp_fp_labels))
class MultiClassPerImageVrdEvaluationTest(tf.test.TestCase):
def setUp(self):
matching_iou_threshold = 0.5
self.eval = per_image_vrd_evaluation.PerImageVRDEvaluation(
matching_iou_threshold)
box_data_type = np.dtype([('subject', 'f4', (4,)), ('object', 'f4', (4,))])
label_data_type = np.dtype([('subject', 'i4'), ('object', 'i4'),
('relation', 'i4')])
self.detected_box_tuples = np.array(
[([0, 0, 1, 1], [1, 1, 2, 2]), ([0, 0, 1.1, 1], [1, 1, 2, 2]),
([1, 1, 2, 2], [0, 0, 1.1, 1]), ([0, 0, 1, 1], [3, 4, 5, 6])],
dtype=box_data_type)
self.detected_class_tuples = np.array(
[(1, 2, 3), (1, 2, 3), (1, 2, 3), (1, 4, 5)], dtype=label_data_type)
self.detected_scores = np.array([0.2, 0.8, 0.1, 0.5], dtype=float)
self.groundtruth_box_tuples = np.array(
[([0, 0, 1, 1], [1, 1, 2, 2]), ([1, 1, 2, 2], [0, 0, 1.1, 1]),
([0, 0, 1, 1], [3, 4, 5, 5.5])],
dtype=box_data_type)
self.groundtruth_class_tuples = np.array(
[(1, 2, 3), (1, 7, 3), (1, 4, 5)], dtype=label_data_type)
def test_tp_fp_eval(self):
scores, tp_fp_labels, mapping = self.eval.compute_detection_tp_fp(
self.detected_box_tuples, self.detected_scores,
self.detected_class_tuples, self.groundtruth_box_tuples,
self.groundtruth_class_tuples)
expected_scores = np.array([0.8, 0.5, 0.2, 0.1], dtype=float)
expected_tp_fp_labels = np.array([True, True, False, False], dtype=bool)
expected_mapping = np.array([1, 3, 0, 2])
self.assertTrue(np.allclose(expected_scores, scores))
self.assertTrue(np.allclose(expected_tp_fp_labels, tp_fp_labels))
self.assertTrue(np.allclose(expected_mapping, mapping))
if __name__ == '__main__':
tf.test.main()
|
PyTorch/Classification/ConvNets/image_classification/models | models | __init__ | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the BSD 3-Clause License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://opensource.org/licenses/BSD-3-Clause
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .entrypoints import nvidia_convnets_processing_utils, nvidia_efficientnet
from .resnet import resnet50, resnext101_32x4d, se_resnext101_32x4d
from .efficientnet import (
efficientnet_b0,
efficientnet_b4,
efficientnet_widese_b0,
efficientnet_widese_b4,
efficientnet_quant_b0,
efficientnet_quant_b4,
)
|
TensorFlow2/LanguageModeling/BERT/official/utils/logs | logs | hooks | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Hook that counts examples per second every N steps or seconds."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf # pylint: disable=g-bad-import-order
from official.utils.logs import logger
class ExamplesPerSecondHook(tf.estimator.SessionRunHook):
"""Hook to print out examples per second.
Total time is tracked and then divided by the total number of steps
to get the average step time and then batch_size is used to determine
the running average of examples per second. The examples per second for the
most recent interval is also logged.
"""
def __init__(self,
batch_size,
every_n_steps=None,
every_n_secs=None,
warm_steps=0,
metric_logger=None):
"""Initializer for ExamplesPerSecondHook.
Args:
batch_size: Total batch size across all workers used to calculate
examples/second from global time.
every_n_steps: Log stats every n steps.
every_n_secs: Log stats every n seconds. Exactly one of the
`every_n_steps` or `every_n_secs` should be set.
warm_steps: The number of steps to be skipped before logging and running
average calculation. warm_steps steps refers to global steps across all
workers, not on each worker
metric_logger: instance of `BenchmarkLogger`, the benchmark logger that
hook should use to write the log. If None, BaseBenchmarkLogger will
be used.
Raises:
ValueError: if neither `every_n_steps` or `every_n_secs` is set, or
both are set.
"""
if (every_n_steps is None) == (every_n_secs is None):
raise ValueError("exactly one of every_n_steps"
" and every_n_secs should be provided.")
self._logger = metric_logger or logger.BaseBenchmarkLogger()
self._timer = tf.estimator.SecondOrStepTimer(
every_steps=every_n_steps, every_secs=every_n_secs)
self._step_train_time = 0
self._total_steps = 0
self._batch_size = batch_size
self._warm_steps = warm_steps
# List of examples per second logged every_n_steps.
self.current_examples_per_sec_list = []
def begin(self):
"""Called once before using the session to check global step."""
self._global_step_tensor = tf.compat.v1.train.get_global_step()
if self._global_step_tensor is None:
raise RuntimeError(
"Global step should be created to use StepCounterHook.")
def before_run(self, run_context): # pylint: disable=unused-argument
"""Called before each call to run().
Args:
run_context: A SessionRunContext object.
Returns:
A SessionRunArgs object or None if never triggered.
"""
return tf.estimator.SessionRunArgs(self._global_step_tensor)
def after_run(self, run_context, run_values): # pylint: disable=unused-argument
"""Called after each call to run().
Args:
run_context: A SessionRunContext object.
run_values: A SessionRunValues object.
"""
global_step = run_values.results
if self._timer.should_trigger_for_step(
global_step) and global_step > self._warm_steps:
elapsed_time, elapsed_steps = self._timer.update_last_triggered_step(
global_step)
if elapsed_time is not None:
self._step_train_time += elapsed_time
self._total_steps += elapsed_steps
# average examples per second is based on the total (accumulative)
# training steps and training time so far
average_examples_per_sec = self._batch_size * (
self._total_steps / self._step_train_time)
# current examples per second is based on the elapsed training steps
# and training time per batch
current_examples_per_sec = self._batch_size * (
elapsed_steps / elapsed_time)
# Logs entries to be read from hook during or after run.
self.current_examples_per_sec_list.append(current_examples_per_sec)
self._logger.log_metric(
"average_examples_per_sec", average_examples_per_sec,
global_step=global_step)
self._logger.log_metric(
"current_examples_per_sec", current_examples_per_sec,
global_step=global_step)
|
TensorFlow2/Recommendation/WideAndDeep/triton/runner | runner | finalizer | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import pathlib
from typing import Dict, List
# method from PEP-366 to support relative import in executed modules
if __name__ == "__main__" and __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .experiment import ExperimentResult
from .logger import LOGGER
from .stages import ResultsType
from .summary import load_results, save_summary
from .task import Task
class Finalizer(abc.ABC):
@abc.abstractmethod
def exec(self, workspace: pathlib.Path, task: Task, results: List[ExperimentResult]):
pass
class ExperimentFinalizer(Finalizer):
"""
Public runner finalizer object.
"""
def exec(self, workspace: pathlib.Path, task: Task, results: List[ExperimentResult]):
results_path = workspace / task.results_dir
self._generate_summary(results_path, results)
self._finalize_task(results_path, task)
def _finalize_task(self, results_path: pathlib.Path, task: Task) -> None:
"""
Finalize task information
Args:
task: Task object
Returns:
None
"""
task.end()
file_path = results_path / task.filename
LOGGER.debug(f"Saving task details to file {file_path}")
task.to_file(file_path)
LOGGER.debug("Done")
LOGGER.info(f"Task details and results stored in {results_path}")
def _generate_summary(self, results_path: pathlib.Path, experiment_results: List[ExperimentResult]):
"""
Generate summary for results collected in all experiments
Args:
results_path: Path where results should be stored
experiment_results: Results collected from experiments
Returns:
"""
performance_offline_results = list()
performance_online_results = list()
results_mapping = {
ResultsType.TRITON_PERFORMANCE_OFFLINE: performance_offline_results,
ResultsType.TRITON_PERFORMANCE_ONLINE: performance_online_results,
}
self._collect_summary_results(experiment_results, results_mapping)
self._prepare_final_results(results_path, results_mapping)
def _collect_summary_results(self, experiment_results: List[ExperimentResult], results_mapping: Dict):
for experiment_result in experiment_results:
experiment = experiment_result.experiment
for result_type, result_path in experiment_result.results.items():
if not result_path.is_file() and not result_path.is_dir():
raise FileNotFoundError(f"Expected file {result_path} not found")
LOGGER.debug(f"Found {result_type} in {result_path} file.")
if result_type not in results_mapping:
LOGGER.debug(f"Results {result_type} for {experiment.experiment_id} are ignored in final summary.")
return
LOGGER.debug(f"Collecting {result_type} results from {result_path} for summary")
result = load_results(
results_path=result_path,
parameters=experiment.parameters,
result_type=result_type,
)
results_mapping[result_type].extend(result)
LOGGER.debug("Done.")
def _prepare_final_results(self, results_path: pathlib.Path, results_mapping: Dict) -> None:
"""
Prepare summary files for offline and online performance
Args:
results_path: Path where results should be stored
results_mapping: Mapping with results type and collected results for given stage
Returns:
None
"""
for results_type, results in results_mapping.items():
save_summary(
result_type=results_type,
results=results,
summary_dir=results_path,
)
|
TensorFlow2/Classification/ConvNets/efficientnet_v1/B0/inference | inference | inference_AMP | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
python3 main.py --cfg config/efficientnet_v1/b0_cfg.py \
--mode predict \
--use_amp \
--use_xla \
--predict_ckpt /model \
--predict_img_dir /infer_data \
--predict_batch_size 50 \
--predict_img_size 224
|
PyTorch/Detection/SSD/ssd | ssd | train | # Copyright (c) 2018-2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from torch.autograd import Variable
import torch
import time
from apex import amp
def train_loop(model, loss_func, scaler, epoch, optim, train_dataloader, val_dataloader, encoder, iteration, logger, args, mean, std):
for nbatch, data in enumerate(train_dataloader):
img = data[0][0][0]
bbox = data[0][1][0]
label = data[0][2][0]
label = label.type(torch.cuda.LongTensor)
bbox_offsets = data[0][3][0]
bbox_offsets = bbox_offsets.cuda()
img.sub_(mean).div_(std)
if not args.no_cuda:
img = img.cuda()
bbox = bbox.cuda()
label = label.cuda()
bbox_offsets = bbox_offsets.cuda()
N = img.shape[0]
if bbox_offsets[-1].item() == 0:
print("No labels in batch")
continue
# output is ([N*8732, 4], [N*8732], need [N, 8732, 4], [N, 8732] respectively
M = bbox.shape[0] // N
bbox = bbox.view(N, M, 4)
label = label.view(N, M)
with torch.cuda.amp.autocast(enabled=args.amp):
if args.data_layout == 'channels_last':
img = img.to(memory_format=torch.channels_last)
ploc, plabel = model(img)
ploc, plabel = ploc.float(), plabel.float()
trans_bbox = bbox.transpose(1, 2).contiguous().cuda()
gloc = Variable(trans_bbox, requires_grad=False)
glabel = Variable(label, requires_grad=False)
loss = loss_func(ploc, plabel, gloc, glabel)
if args.warmup is not None:
warmup(optim, args.warmup, iteration, args.learning_rate)
scaler.scale(loss).backward()
scaler.step(optim)
scaler.update()
optim.zero_grad()
if args.local_rank == 0:
logger.update_iter(epoch, iteration, loss.item())
iteration += 1
return iteration
def benchmark_train_loop(model, loss_func, scaler, epoch, optim, train_dataloader, val_dataloader, encoder, iteration, logger, args, mean, std):
start_time = None
# tensor for results
result = torch.zeros((1,)).cuda()
for nbatch, data in enumerate(loop(train_dataloader)):
if nbatch >= args.benchmark_warmup:
torch.cuda.synchronize()
start_time = time.time()
img = data[0][0][0]
bbox = data[0][1][0]
label = data[0][2][0]
label = label.type(torch.cuda.LongTensor)
bbox_offsets = data[0][3][0]
bbox_offsets = bbox_offsets.cuda()
img.sub_(mean).div_(std)
if not args.no_cuda:
img = img.cuda()
bbox = bbox.cuda()
label = label.cuda()
bbox_offsets = bbox_offsets.cuda()
N = img.shape[0]
if bbox_offsets[-1].item() == 0:
print("No labels in batch")
continue
# output is ([N*8732, 4], [N*8732], need [N, 8732, 4], [N, 8732] respectively
M = bbox.shape[0] // N
bbox = bbox.view(N, M, 4)
label = label.view(N, M)
with torch.cuda.amp.autocast(enabled=args.amp):
if args.data_layout == 'channels_last':
img = img.to(memory_format=torch.channels_last)
ploc, plabel = model(img)
ploc, plabel = ploc.float(), plabel.float()
trans_bbox = bbox.transpose(1, 2).contiguous().cuda()
gloc = Variable(trans_bbox, requires_grad=False)
glabel = Variable(label, requires_grad=False)
loss = loss_func(ploc, plabel, gloc, glabel)
if args.warmup is not None:
warmup(optim, args.warmup, iteration, args.learning_rate)
scaler.scale(loss).backward()
scaler.step(optim)
scaler.update()
optim.zero_grad()
if nbatch >= args.benchmark_warmup + args.benchmark_iterations:
break
if nbatch >= args.benchmark_warmup:
torch.cuda.synchronize()
logger.update(args.batch_size*args.N_gpu, time.time() - start_time)
result.data[0] = logger.print_result()
if args.N_gpu > 1:
torch.distributed.reduce(result, 0)
if args.local_rank == 0:
print('Training performance = {} FPS'.format(float(result.data[0])))
def loop(dataloader, reset=True):
while True:
for data in dataloader:
yield data
if reset:
dataloader.reset()
def benchmark_inference_loop(model, loss_func, scaler, epoch, optim, train_dataloader, val_dataloader, encoder, iteration, logger, args, mean, std):
assert args.N_gpu == 1, 'Inference benchmark only on 1 gpu'
model.eval()
val_datas = loop(val_dataloader, False)
for i in range(args.benchmark_warmup + args.benchmark_iterations):
torch.cuda.synchronize()
start_time = time.time()
data = next(val_datas)
img = data[0]
with torch.no_grad():
if not args.no_cuda:
img = img.cuda()
img.sub_(mean).div_(std)
with torch.cuda.amp.autocast(enabled=args.amp):
_ = model(img)
torch.cuda.synchronize()
end_time = time.time()
if i >= args.benchmark_warmup:
logger.update(args.eval_batch_size, end_time - start_time)
logger.print_result()
def warmup(optim, warmup_iters, iteration, base_lr):
if iteration < warmup_iters:
new_lr = 1. * base_lr / warmup_iters * iteration
for param_group in optim.param_groups:
param_group['lr'] = new_lr
def load_checkpoint(model, checkpoint):
"""
Load model from checkpoint.
"""
print("loading model checkpoint", checkpoint)
od = torch.load(checkpoint)
# remove proceeding 'N.' from checkpoint that comes from DDP wrapper
saved_model = od["model"]
model.load_state_dict(saved_model)
def tencent_trick(model):
"""
Divide parameters into 2 groups.
First group is BNs and all biases.
Second group is the remaining model's parameters.
Weight decay will be disabled in first group (aka tencent trick).
"""
decay, no_decay = [], []
for name, param in model.named_parameters():
if not param.requires_grad:
continue # frozen weights
if len(param.shape) == 1 or name.endswith(".bias"):
no_decay.append(param)
else:
decay.append(param)
return [{'params': no_decay, 'weight_decay': 0.0},
{'params': decay}]
|
Tools/PyTorch/TimeSeriesPredictionPlatform/triton | triton | metrics | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import pandas as pd
import numpy as np
import pickle
import argparse
import hydra
import torch
from triton.deployment_toolkit.core import BaseMetricsCalculator
from omegaconf import OmegaConf
def update_argparser(parser):
parser.add_argument("--model-dir", type=str, help="Path to the model directory you would like to use (likely in outputs)", required=True)
class MetricsCalculator(BaseMetricsCalculator):
def __init__(self, model_dir):
with open(os.path.join(model_dir, ".hydra/config_merged.yaml"), "rb") as f:
self.config = OmegaConf.load(f)
train, valid, test = hydra.utils.call(self.config.dataset)
del train, valid
self.evaluator = hydra.utils.call(self.config.evaluator, test_data=test)
self.predictions = []
self.targets = []
self.ids = []
self.weights = []
@property
def metrics(self):
targets = np.concatenate(self.targets, axis=0)
predictions = np.concatenate(self.predictions, axis=0)
weights = np.concatenate(self.weights, axis=0)
ids = np.concatenate(self.ids, axis=0)
if np.isnan(weights).any():
weights = np.empty([0])
return self.evaluator.evaluate(targets, predictions, ids, weights)
def update(
self,
ids,
y_pred,
x,
y_real,
):
#can probably just pass all of this to the evaluator main class
self.targets.append(y_real['target__0'][:,:,0][:,:,np.newaxis])
self.ids.append(ids)
self.weights.append(x["weight__9"])
preds = y_pred["target__0"]
self.predictions.append(preds)
# return self.metrics
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/test | test | Blending_test | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "UnitTest.hpp"
#include "blending.h"
#include "cudaMemory.h"
#include <vector>
using namespace tts;
/******************************************************************************
* UNIT TEST ******************************************************************
*****************************************************************************/
TEST(noOverlapNoOffsetBatchSize1)
{
const int chunkSize = 4000;
const int batchSize = 1;
std::vector<float> samplesHost(chunkSize * batchSize);
for (size_t i = 0; i < samplesHost.size(); ++i) {
samplesHost[i] = static_cast<float>(i % 1001) / 1000.0f;
}
CudaMemory<float> samplesDevice(samplesHost);
CudaMemory<float> outDevice(samplesHost.size());
Blending::linear(
batchSize,
samplesDevice.data(),
outDevice.data(),
chunkSize,
0,
chunkSize,
0,
0);
const std::vector<float> outHost = outDevice.toHost();
for (size_t i = 0; i < samplesHost.size(); ++i) {
EXPECT_NEAR(samplesHost[i], outHost[i], 1e-6f);
}
}
TEST(noOverlapNoOffsetBatchSize4)
{
const int chunkSize = 4000;
const int batchSize = 4;
std::vector<float> samplesHost(chunkSize * batchSize);
for (size_t i = 0; i < samplesHost.size(); ++i) {
samplesHost[i] = static_cast<float>(i % 1001) / 1000.0f;
}
CudaMemory<float> samplesDevice(samplesHost);
CudaMemory<float> outDevice(samplesHost.size());
Blending::linear(
batchSize,
samplesDevice.data(),
outDevice.data(),
chunkSize,
0,
chunkSize,
0,
0);
const std::vector<float> outHost = outDevice.toHost();
for (size_t i = 0; i < samplesHost.size(); ++i) {
EXPECT_NEAR(samplesHost[i], outHost[i], 1e-6f);
}
}
TEST(noOverlapOneOffsetBatchSize4)
{
const int chunkSize = 4000;
const int batchSize = 4;
std::vector<float> samplesHost(chunkSize * batchSize);
for (size_t i = 0; i < samplesHost.size(); ++i) {
samplesHost[i] = static_cast<float>(i % 1001) / 1000.0f;
}
CudaMemory<float> samplesDevice(samplesHost);
CudaMemory<float> outDevice(samplesHost.size() * 2);
outDevice.zero();
Blending::linear(
batchSize,
samplesDevice.data(),
outDevice.data(),
chunkSize,
0,
2 * chunkSize,
chunkSize,
0);
const std::vector<float> outHost = outDevice.toHost();
for (int b = 0; b < batchSize; ++b) {
for (int i = 0; i < chunkSize; ++i) {
const int j = b * (chunkSize * 2) + i;
EXPECT_EQ(0.0f, outHost[j]) << "i = " << i;
}
for (int i = chunkSize; i < chunkSize * 2; ++i) {
const int j = b * (chunkSize * 2) + i;
const int k = b * chunkSize + (i - chunkSize);
EXPECT_NEAR(samplesHost[k], outHost[j], 1e-6f) << "i = " << i;
}
}
}
|
PyTorch/Detection/Efficientdet/effdet/csrc/nms/cuda | cuda | nms | // Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <ATen/ATen.h>
#include <ATen/cuda/CUDAContext.h>
#include <THC/THC.h>
#include <THC/THCDeviceUtils.cuh>
#include <vector>
#include <iostream>
int const threadsPerBlock = sizeof(unsigned long long) * 8;
__device__ inline float devIoU(float const * const a, float const * const b) {
float left = max(a[0], b[0]), right = min(a[2], b[2]);
float top = max(a[1], b[1]), bottom = min(a[3], b[3]);
float width = max(right - left + 1, 0.f), height = max(bottom - top + 1, 0.f);
float interS = width * height;
float Sa = (a[2] - a[0] + 1) * (a[3] - a[1] + 1);
float Sb = (b[2] - b[0] + 1) * (b[3] - b[1] + 1);
return interS / (Sa + Sb - interS);
}
__global__ void nms_kernel(const int n_boxes, const float nms_overlap_thresh,
const float *dev_boxes, unsigned long long *dev_mask) {
const int row_start = blockIdx.y;
const int col_start = blockIdx.x;
// if (row_start > col_start) return;
const int row_size =
min(n_boxes - row_start * threadsPerBlock, threadsPerBlock);
const int col_size =
min(n_boxes - col_start * threadsPerBlock, threadsPerBlock);
__shared__ float block_boxes[threadsPerBlock * 5];
if (threadIdx.x < col_size) {
block_boxes[threadIdx.x * 5 + 0] =
dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 5 + 0];
block_boxes[threadIdx.x * 5 + 1] =
dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 5 + 1];
block_boxes[threadIdx.x * 5 + 2] =
dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 5 + 2];
block_boxes[threadIdx.x * 5 + 3] =
dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 5 + 3];
block_boxes[threadIdx.x * 5 + 4] =
dev_boxes[(threadsPerBlock * col_start + threadIdx.x) * 5 + 4];
}
__syncthreads();
if (threadIdx.x < row_size) {
const int cur_box_idx = threadsPerBlock * row_start + threadIdx.x;
const float *cur_box = dev_boxes + cur_box_idx * 5;
int i = 0;
unsigned long long t = 0;
int start = 0;
if (row_start == col_start) {
start = threadIdx.x + 1;
}
for (i = start; i < col_size; i++) {
if (devIoU(cur_box, block_boxes + i * 5) > nms_overlap_thresh) {
t |= 1ULL << i;
}
}
const int col_blocks = THCCeilDiv(n_boxes, threadsPerBlock);
dev_mask[cur_box_idx * col_blocks + col_start] = t;
}
}
// boxes is a N x 5 tensor
at::Tensor nms_cuda(const at::Tensor boxes, float nms_overlap_thresh) {
using scalar_t = float;
AT_ASSERTM(boxes.is_cuda(), "boxes must be a CUDA tensor");
auto scores = boxes.select(1, 4);
auto order_t = std::get<1>(scores.sort(0, /* descending=*/true));
auto boxes_sorted = boxes.index_select(0, order_t);
int boxes_num = boxes.size(0);
const int col_blocks = THCCeilDiv(boxes_num, threadsPerBlock);
scalar_t* boxes_dev = boxes_sorted.data_ptr<scalar_t>();
THCState *state = at::globalContext().lazyInitCUDA(); // TODO replace with getTHCState
unsigned long long* mask_dev = NULL;
//THCudaCheck(THCudaMalloc(state, (void**) &mask_dev,
// boxes_num * col_blocks * sizeof(unsigned long long)));
mask_dev = (unsigned long long*) THCudaMalloc(state, boxes_num * col_blocks * sizeof(unsigned long long));
dim3 blocks(THCCeilDiv(boxes_num, threadsPerBlock),
THCCeilDiv(boxes_num, threadsPerBlock));
dim3 threads(threadsPerBlock);
nms_kernel<<<blocks, threads>>>(boxes_num,
nms_overlap_thresh,
boxes_dev,
mask_dev);
std::vector<unsigned long long> mask_host(boxes_num * col_blocks);
THCudaCheck(cudaMemcpy(&mask_host[0],
mask_dev,
sizeof(unsigned long long) * boxes_num * col_blocks,
cudaMemcpyDeviceToHost));
std::vector<unsigned long long> remv(col_blocks);
memset(&remv[0], 0, sizeof(unsigned long long) * col_blocks);
at::Tensor keep = at::empty({boxes_num}, boxes.options().dtype(at::kLong).device(at::kCPU));
int64_t* keep_out = keep.data_ptr<int64_t>();
int num_to_keep = 0;
for (int i = 0; i < boxes_num; i++) {
int nblock = i / threadsPerBlock;
int inblock = i % threadsPerBlock;
if (!(remv[nblock] & (1ULL << inblock))) {
keep_out[num_to_keep++] = i;
unsigned long long *p = &mask_host[0] + i * col_blocks;
for (int j = nblock; j < col_blocks; j++) {
remv[j] |= p[j];
}
}
}
THCudaFree(state, mask_dev);
// TODO improve this part
return std::get<0>(order_t.index({
keep.narrow(/*dim=*/0, /*start=*/0, /*length=*/num_to_keep).to(
order_t.device(), keep.scalar_type())
}).sort(0, false));
}
|
TensorFlow/Detection/SSD/models/research/slim/datasets | datasets | build_imagenet_data | # Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Converts ImageNet data to TFRecords file format with Example protos.
The raw ImageNet data set is expected to reside in JPEG files located in the
following directory structure.
data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
...
where 'n01440764' is the unique synset label associated with
these images.
The training data set consists of 1000 sub-directories (i.e. labels)
each containing 1200 JPEG images for a total of 1.2M JPEG images.
The evaluation data set consists of 1000 sub-directories (i.e. labels)
each containing 50 JPEG images for a total of 50K JPEG images.
This TensorFlow script converts the training and evaluation data into
a sharded data set consisting of 1024 and 128 TFRecord files, respectively.
train_directory/train-00000-of-01024
train_directory/train-00001-of-01024
...
train_directory/train-00127-of-01024
and
validation_directory/validation-00000-of-00128
validation_directory/validation-00001-of-00128
...
validation_directory/validation-00127-of-00128
Each validation TFRecord file contains ~390 records. Each training TFREcord
file contains ~1250 records. Each record within the TFRecord file is a
serialized Example proto. The Example proto contains the following fields:
image/encoded: string containing JPEG encoded image in RGB colorspace
image/height: integer, image height in pixels
image/width: integer, image width in pixels
image/colorspace: string, specifying the colorspace, always 'RGB'
image/channels: integer, specifying the number of channels, always 3
image/format: string, specifying the format, always'JPEG'
image/filename: string containing the basename of the image file
e.g. 'n01440764_10026.JPEG' or 'ILSVRC2012_val_00000293.JPEG'
image/class/label: integer specifying the index in a classification layer.
The label ranges from [1, 1000] where 0 is not used.
image/class/synset: string specifying the unique ID of the label,
e.g. 'n01440764'
image/class/text: string specifying the human-readable version of the label
e.g. 'red fox, Vulpes vulpes'
image/object/bbox/xmin: list of integers specifying the 0+ human annotated
bounding boxes
image/object/bbox/xmax: list of integers specifying the 0+ human annotated
bounding boxes
image/object/bbox/ymin: list of integers specifying the 0+ human annotated
bounding boxes
image/object/bbox/ymax: list of integers specifying the 0+ human annotated
bounding boxes
image/object/bbox/label: integer specifying the index in a classification
layer. The label ranges from [1, 1000] where 0 is not used. Note this is
always identical to the image label.
Note that the length of xmin is identical to the length of xmax, ymin and ymax
for each example.
Running this script using 16 threads may take around ~2.5 hours on a HP Z420.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import os
import random
import sys
import threading
import numpy as np
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
tf.app.flags.DEFINE_string('train_directory', '/tmp/',
'Training data directory')
tf.app.flags.DEFINE_string('validation_directory', '/tmp/',
'Validation data directory')
tf.app.flags.DEFINE_string('output_directory', '/tmp/',
'Output data directory')
tf.app.flags.DEFINE_integer('train_shards', 1024,
'Number of shards in training TFRecord files.')
tf.app.flags.DEFINE_integer('validation_shards', 128,
'Number of shards in validation TFRecord files.')
tf.app.flags.DEFINE_integer('num_threads', 8,
'Number of threads to preprocess the images.')
# The labels file contains a list of valid labels are held in this file.
# Assumes that the file contains entries as such:
# n01440764
# n01443537
# n01484850
# where each line corresponds to a label expressed as a synset. We map
# each synset contained in the file to an integer (based on the alphabetical
# ordering). See below for details.
tf.app.flags.DEFINE_string('labels_file',
'imagenet_lsvrc_2015_synsets.txt',
'Labels file')
# This file containing mapping from synset to human-readable label.
# Assumes each line of the file looks like:
#
# n02119247 black fox
# n02119359 silver fox
# n02119477 red fox, Vulpes fulva
#
# where each line corresponds to a unique mapping. Note that each line is
# formatted as <synset>\t<human readable label>.
tf.app.flags.DEFINE_string('imagenet_metadata_file',
'imagenet_metadata.txt',
'ImageNet metadata file')
# This file is the output of process_bounding_box.py
# Assumes each line of the file looks like:
#
# n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940
#
# where each line corresponds to one bounding box annotation associated
# with an image. Each line can be parsed as:
#
# <JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax>
#
# Note that there might exist mulitple bounding box annotations associated
# with an image file.
tf.app.flags.DEFINE_string('bounding_box_file',
'./imagenet_2012_bounding_boxes.csv',
'Bounding box file')
FLAGS = tf.app.flags.FLAGS
def _int64_feature(value):
"""Wrapper for inserting int64 features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def _float_feature(value):
"""Wrapper for inserting float features into Example proto."""
if not isinstance(value, list):
value = [value]
return tf.train.Feature(float_list=tf.train.FloatList(value=value))
def _bytes_feature(value):
"""Wrapper for inserting bytes features into Example proto."""
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
def _convert_to_example(filename, image_buffer, label, synset, human, bbox,
height, width):
"""Build an Example proto for an example.
Args:
filename: string, path to an image file, e.g., '/path/to/example.JPG'
image_buffer: string, JPEG encoding of RGB image
label: integer, identifier for the ground truth for the network
synset: string, unique WordNet ID specifying the label, e.g., 'n02323233'
human: string, human-readable label, e.g., 'red fox, Vulpes vulpes'
bbox: list of bounding boxes; each box is a list of integers
specifying [xmin, ymin, xmax, ymax]. All boxes are assumed to belong to
the same label as the image label.
height: integer, image height in pixels
width: integer, image width in pixels
Returns:
Example proto
"""
xmin = []
ymin = []
xmax = []
ymax = []
for b in bbox:
assert len(b) == 4
# pylint: disable=expression-not-assigned
[l.append(point) for l, point in zip([xmin, ymin, xmax, ymax], b)]
# pylint: enable=expression-not-assigned
colorspace = 'RGB'
channels = 3
image_format = 'JPEG'
example = tf.train.Example(features=tf.train.Features(feature={
'image/height': _int64_feature(height),
'image/width': _int64_feature(width),
'image/colorspace': _bytes_feature(colorspace),
'image/channels': _int64_feature(channels),
'image/class/label': _int64_feature(label),
'image/class/synset': _bytes_feature(synset),
'image/class/text': _bytes_feature(human),
'image/object/bbox/xmin': _float_feature(xmin),
'image/object/bbox/xmax': _float_feature(xmax),
'image/object/bbox/ymin': _float_feature(ymin),
'image/object/bbox/ymax': _float_feature(ymax),
'image/object/bbox/label': _int64_feature([label] * len(xmin)),
'image/format': _bytes_feature(image_format),
'image/filename': _bytes_feature(os.path.basename(filename)),
'image/encoded': _bytes_feature(image_buffer)}))
return example
class ImageCoder(object):
"""Helper class that provides TensorFlow image coding utilities."""
def __init__(self):
# Create a single Session to run all image coding calls.
self._sess = tf.Session()
# Initializes function that converts PNG to JPEG data.
self._png_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_png(self._png_data, channels=3)
self._png_to_jpeg = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that converts CMYK JPEG data to RGB JPEG data.
self._cmyk_data = tf.placeholder(dtype=tf.string)
image = tf.image.decode_jpeg(self._cmyk_data, channels=0)
self._cmyk_to_rgb = tf.image.encode_jpeg(image, format='rgb', quality=100)
# Initializes function that decodes RGB JPEG data.
self._decode_jpeg_data = tf.placeholder(dtype=tf.string)
self._decode_jpeg = tf.image.decode_jpeg(self._decode_jpeg_data, channels=3)
def png_to_jpeg(self, image_data):
return self._sess.run(self._png_to_jpeg,
feed_dict={self._png_data: image_data})
def cmyk_to_rgb(self, image_data):
return self._sess.run(self._cmyk_to_rgb,
feed_dict={self._cmyk_data: image_data})
def decode_jpeg(self, image_data):
image = self._sess.run(self._decode_jpeg,
feed_dict={self._decode_jpeg_data: image_data})
assert len(image.shape) == 3
assert image.shape[2] == 3
return image
def _is_png(filename):
"""Determine if a file contains a PNG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a PNG.
"""
# File list from:
# https://groups.google.com/forum/embed/?place=forum/torch7#!topic/torch7/fOSTXHIESSU
return 'n02105855_2933.JPEG' in filename
def _is_cmyk(filename):
"""Determine if file contains a CMYK JPEG format image.
Args:
filename: string, path of the image file.
Returns:
boolean indicating if the image is a JPEG encoded with CMYK color space.
"""
# File list from:
# https://github.com/cytsai/ilsvrc-cmyk-image-list
blacklist = ['n01739381_1309.JPEG', 'n02077923_14822.JPEG',
'n02447366_23489.JPEG', 'n02492035_15739.JPEG',
'n02747177_10752.JPEG', 'n03018349_4028.JPEG',
'n03062245_4620.JPEG', 'n03347037_9675.JPEG',
'n03467068_12171.JPEG', 'n03529860_11437.JPEG',
'n03544143_17228.JPEG', 'n03633091_5218.JPEG',
'n03710637_5125.JPEG', 'n03961711_5286.JPEG',
'n04033995_2932.JPEG', 'n04258138_17003.JPEG',
'n04264628_27969.JPEG', 'n04336792_7448.JPEG',
'n04371774_5854.JPEG', 'n04596742_4225.JPEG',
'n07583066_647.JPEG', 'n13037406_4650.JPEG']
return filename.split('/')[-1] in blacklist
def _process_image(filename, coder):
"""Process a single image file.
Args:
filename: string, path to an image file e.g., '/path/to/example.JPG'.
coder: instance of ImageCoder to provide TensorFlow image coding utils.
Returns:
image_buffer: string, JPEG encoding of RGB image.
height: integer, image height in pixels.
width: integer, image width in pixels.
"""
# Read the image file.
image_data = tf.gfile.FastGFile(filename, 'r').read()
# Clean the dirty data.
if _is_png(filename):
# 1 image is a PNG.
print('Converting PNG to JPEG for %s' % filename)
image_data = coder.png_to_jpeg(image_data)
elif _is_cmyk(filename):
# 22 JPEG images are in CMYK colorspace.
print('Converting CMYK to RGB for %s' % filename)
image_data = coder.cmyk_to_rgb(image_data)
# Decode the RGB JPEG.
image = coder.decode_jpeg(image_data)
# Check that image converted to RGB
assert len(image.shape) == 3
height = image.shape[0]
width = image.shape[1]
assert image.shape[2] == 3
return image_data, height, width
def _process_image_files_batch(coder, thread_index, ranges, name, filenames,
synsets, labels, humans, bboxes, num_shards):
"""Processes and saves list of images as TFRecord in 1 thread.
Args:
coder: instance of ImageCoder to provide TensorFlow image coding utils.
thread_index: integer, unique batch to run index is within [0, len(ranges)).
ranges: list of pairs of integers specifying ranges of each batches to
analyze in parallel.
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
synsets: list of strings; each string is a unique WordNet ID
labels: list of integer; each integer identifies the ground truth
humans: list of strings; each string is a human-readable label
bboxes: list of bounding boxes for each image. Note that each entry in this
list might contain from 0+ entries corresponding to the number of bounding
box annotations for the image.
num_shards: integer number of shards for this data set.
"""
# Each thread produces N shards where N = int(num_shards / num_threads).
# For instance, if num_shards = 128, and the num_threads = 2, then the first
# thread would produce shards [0, 64).
num_threads = len(ranges)
assert not num_shards % num_threads
num_shards_per_batch = int(num_shards / num_threads)
shard_ranges = np.linspace(ranges[thread_index][0],
ranges[thread_index][1],
num_shards_per_batch + 1).astype(int)
num_files_in_thread = ranges[thread_index][1] - ranges[thread_index][0]
counter = 0
for s in xrange(num_shards_per_batch):
# Generate a sharded version of the file name, e.g. 'train-00002-of-00010'
shard = thread_index * num_shards_per_batch + s
output_filename = '%s-%.5d-of-%.5d' % (name, shard, num_shards)
output_file = os.path.join(FLAGS.output_directory, output_filename)
writer = tf.python_io.TFRecordWriter(output_file)
shard_counter = 0
files_in_shard = np.arange(shard_ranges[s], shard_ranges[s + 1], dtype=int)
for i in files_in_shard:
filename = filenames[i]
label = labels[i]
synset = synsets[i]
human = humans[i]
bbox = bboxes[i]
image_buffer, height, width = _process_image(filename, coder)
example = _convert_to_example(filename, image_buffer, label,
synset, human, bbox,
height, width)
writer.write(example.SerializeToString())
shard_counter += 1
counter += 1
if not counter % 1000:
print('%s [thread %d]: Processed %d of %d images in thread batch.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
writer.close()
print('%s [thread %d]: Wrote %d images to %s' %
(datetime.now(), thread_index, shard_counter, output_file))
sys.stdout.flush()
shard_counter = 0
print('%s [thread %d]: Wrote %d images to %d shards.' %
(datetime.now(), thread_index, counter, num_files_in_thread))
sys.stdout.flush()
def _process_image_files(name, filenames, synsets, labels, humans,
bboxes, num_shards):
"""Process and save list of images as TFRecord of Example protos.
Args:
name: string, unique identifier specifying the data set
filenames: list of strings; each string is a path to an image file
synsets: list of strings; each string is a unique WordNet ID
labels: list of integer; each integer identifies the ground truth
humans: list of strings; each string is a human-readable label
bboxes: list of bounding boxes for each image. Note that each entry in this
list might contain from 0+ entries corresponding to the number of bounding
box annotations for the image.
num_shards: integer number of shards for this data set.
"""
assert len(filenames) == len(synsets)
assert len(filenames) == len(labels)
assert len(filenames) == len(humans)
assert len(filenames) == len(bboxes)
# Break all images into batches with a [ranges[i][0], ranges[i][1]].
spacing = np.linspace(0, len(filenames), FLAGS.num_threads + 1).astype(np.int)
ranges = []
threads = []
for i in xrange(len(spacing) - 1):
ranges.append([spacing[i], spacing[i+1]])
# Launch a thread for each batch.
print('Launching %d threads for spacings: %s' % (FLAGS.num_threads, ranges))
sys.stdout.flush()
# Create a mechanism for monitoring when all threads are finished.
coord = tf.train.Coordinator()
# Create a generic TensorFlow-based utility for converting all image codings.
coder = ImageCoder()
threads = []
for thread_index in xrange(len(ranges)):
args = (coder, thread_index, ranges, name, filenames,
synsets, labels, humans, bboxes, num_shards)
t = threading.Thread(target=_process_image_files_batch, args=args)
t.start()
threads.append(t)
# Wait for all the threads to terminate.
coord.join(threads)
print('%s: Finished writing all %d images in data set.' %
(datetime.now(), len(filenames)))
sys.stdout.flush()
def _find_image_files(data_dir, labels_file):
"""Build a list of all images files and labels in the data set.
Args:
data_dir: string, path to the root directory of images.
Assumes that the ImageNet data set resides in JPEG files located in
the following directory structure.
data_dir/n01440764/ILSVRC2012_val_00000293.JPEG
data_dir/n01440764/ILSVRC2012_val_00000543.JPEG
where 'n01440764' is the unique synset label associated with these images.
labels_file: string, path to the labels file.
The list of valid labels are held in this file. Assumes that the file
contains entries as such:
n01440764
n01443537
n01484850
where each line corresponds to a label expressed as a synset. We map
each synset contained in the file to an integer (based on the alphabetical
ordering) starting with the integer 1 corresponding to the synset
contained in the first line.
The reason we start the integer labels at 1 is to reserve label 0 as an
unused background class.
Returns:
filenames: list of strings; each string is a path to an image file.
synsets: list of strings; each string is a unique WordNet ID.
labels: list of integer; each integer identifies the ground truth.
"""
print('Determining list of input files and labels from %s.' % data_dir)
challenge_synsets = [l.strip() for l in
tf.gfile.FastGFile(labels_file, 'r').readlines()]
labels = []
filenames = []
synsets = []
# Leave label index 0 empty as a background class.
label_index = 1
# Construct the list of JPEG files and labels.
for synset in challenge_synsets:
jpeg_file_path = '%s/%s/*.JPEG' % (data_dir, synset)
matching_files = tf.gfile.Glob(jpeg_file_path)
labels.extend([label_index] * len(matching_files))
synsets.extend([synset] * len(matching_files))
filenames.extend(matching_files)
if not label_index % 100:
print('Finished finding files in %d of %d classes.' % (
label_index, len(challenge_synsets)))
label_index += 1
# Shuffle the ordering of all image files in order to guarantee
# random ordering of the images with respect to label in the
# saved TFRecord files. Make the randomization repeatable.
shuffled_index = range(len(filenames))
random.seed(12345)
random.shuffle(shuffled_index)
filenames = [filenames[i] for i in shuffled_index]
synsets = [synsets[i] for i in shuffled_index]
labels = [labels[i] for i in shuffled_index]
print('Found %d JPEG files across %d labels inside %s.' %
(len(filenames), len(challenge_synsets), data_dir))
return filenames, synsets, labels
def _find_human_readable_labels(synsets, synset_to_human):
"""Build a list of human-readable labels.
Args:
synsets: list of strings; each string is a unique WordNet ID.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red fox, Vulpes vulpes'
Returns:
List of human-readable strings corresponding to each synset.
"""
humans = []
for s in synsets:
assert s in synset_to_human, ('Failed to find: %s' % s)
humans.append(synset_to_human[s])
return humans
def _find_image_bounding_boxes(filenames, image_to_bboxes):
"""Find the bounding boxes for a given image file.
Args:
filenames: list of strings; each string is a path to an image file.
image_to_bboxes: dictionary mapping image file names to a list of
bounding boxes. This list contains 0+ bounding boxes.
Returns:
List of bounding boxes for each image. Note that each entry in this
list might contain from 0+ entries corresponding to the number of bounding
box annotations for the image.
"""
num_image_bbox = 0
bboxes = []
for f in filenames:
basename = os.path.basename(f)
if basename in image_to_bboxes:
bboxes.append(image_to_bboxes[basename])
num_image_bbox += 1
else:
bboxes.append([])
print('Found %d images with bboxes out of %d images' % (
num_image_bbox, len(filenames)))
return bboxes
def _process_dataset(name, directory, num_shards, synset_to_human,
image_to_bboxes):
"""Process a complete data set and save it as a TFRecord.
Args:
name: string, unique identifier specifying the data set.
directory: string, root path to the data set.
num_shards: integer number of shards for this data set.
synset_to_human: dict of synset to human labels, e.g.,
'n02119022' --> 'red fox, Vulpes vulpes'
image_to_bboxes: dictionary mapping image file names to a list of
bounding boxes. This list contains 0+ bounding boxes.
"""
filenames, synsets, labels = _find_image_files(directory, FLAGS.labels_file)
humans = _find_human_readable_labels(synsets, synset_to_human)
bboxes = _find_image_bounding_boxes(filenames, image_to_bboxes)
_process_image_files(name, filenames, synsets, labels,
humans, bboxes, num_shards)
def _build_synset_lookup(imagenet_metadata_file):
"""Build lookup for synset to human-readable label.
Args:
imagenet_metadata_file: string, path to file containing mapping from
synset to human-readable label.
Assumes each line of the file looks like:
n02119247 black fox
n02119359 silver fox
n02119477 red fox, Vulpes fulva
where each line corresponds to a unique mapping. Note that each line is
formatted as <synset>\t<human readable label>.
Returns:
Dictionary of synset to human labels, such as:
'n02119022' --> 'red fox, Vulpes vulpes'
"""
lines = tf.gfile.FastGFile(imagenet_metadata_file, 'r').readlines()
synset_to_human = {}
for l in lines:
if l:
parts = l.strip().split('\t')
assert len(parts) == 2
synset = parts[0]
human = parts[1]
synset_to_human[synset] = human
return synset_to_human
def _build_bounding_box_lookup(bounding_box_file):
"""Build a lookup from image file to bounding boxes.
Args:
bounding_box_file: string, path to file with bounding boxes annotations.
Assumes each line of the file looks like:
n00007846_64193.JPEG,0.0060,0.2620,0.7545,0.9940
where each line corresponds to one bounding box annotation associated
with an image. Each line can be parsed as:
<JPEG file name>, <xmin>, <ymin>, <xmax>, <ymax>
Note that there might exist mulitple bounding box annotations associated
with an image file. This file is the output of process_bounding_boxes.py.
Returns:
Dictionary mapping image file names to a list of bounding boxes. This list
contains 0+ bounding boxes.
"""
lines = tf.gfile.FastGFile(bounding_box_file, 'r').readlines()
images_to_bboxes = {}
num_bbox = 0
num_image = 0
for l in lines:
if l:
parts = l.split(',')
assert len(parts) == 5, ('Failed to parse: %s' % l)
filename = parts[0]
xmin = float(parts[1])
ymin = float(parts[2])
xmax = float(parts[3])
ymax = float(parts[4])
box = [xmin, ymin, xmax, ymax]
if filename not in images_to_bboxes:
images_to_bboxes[filename] = []
num_image += 1
images_to_bboxes[filename].append(box)
num_bbox += 1
print('Successfully read %d bounding boxes '
'across %d images.' % (num_bbox, num_image))
return images_to_bboxes
def main(unused_argv):
assert not FLAGS.train_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with FLAGS.train_shards')
assert not FLAGS.validation_shards % FLAGS.num_threads, (
'Please make the FLAGS.num_threads commensurate with '
'FLAGS.validation_shards')
print('Saving results to %s' % FLAGS.output_directory)
# Build a map from synset to human-readable label.
synset_to_human = _build_synset_lookup(FLAGS.imagenet_metadata_file)
image_to_bboxes = _build_bounding_box_lookup(FLAGS.bounding_box_file)
# Run it!
_process_dataset('validation', FLAGS.validation_directory,
FLAGS.validation_shards, synset_to_human, image_to_bboxes)
_process_dataset('train', FLAGS.train_directory, FLAGS.train_shards,
synset_to_human, image_to_bboxes)
if __name__ == '__main__':
tf.app.run()
|
Tools/PyTorch/TimeSeriesPredictionPlatform/models/tft_pyt/triton/deployment_toolkit | deployment_toolkit | dump | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import abc
import json
import pickle
import threading
from pathlib import Path
from typing import Dict, Iterator, List, Union
import numpy as np
MB2B = 2 ** 20
B2MB = 1 / MB2B
FLUSH_THRESHOLD_B = 256 * MB2B
def _validate_batch(name: str, value: Union[list, np.ndarray]):
if not isinstance(value, (list, np.ndarray)):
raise ValueError(f"Values shall be lists or np.ndarrays; current type {type(value)}")
def _validate_prefix_data(prefix_data: Dict[str, List[np.ndarray]]):
batch_sizes_per_io_name = {name: [len(batch) for batch in batches] for name, batches in prefix_data.items()}
names = list(batch_sizes_per_io_name)
for io_name in names:
for batch_idx, batch_size in enumerate(batch_sizes_per_io_name[io_name]):
if not all([batch_sizes_per_io_name[other_name][batch_idx] == batch_size for other_name in names]):
non_equal_batch_sizes = {
other_name: batch_sizes_per_io_name[other_name][batch_idx] for other_name in names
}
non_equal_batch_sizes_str = ", ".join(
[f"{name}={batch_size}" for name, batch_size in non_equal_batch_sizes.items()]
)
raise ValueError(
"All inputs/outputs should have same number of batches with equal batch_size. "
f"At batch_idx={batch_idx} there are batch_sizes: {non_equal_batch_sizes_str}"
)
# ensure if each io has same number of batches with equal size
def _get_nitems_and_batches(prefix_data: Dict[str, List[np.ndarray]]):
nitems = 0
nbatches = 0
if prefix_data:
nitems_per_io_name = {name: sum(len(batch) for batch in batches) for name, batches in prefix_data.items()}
nbatches_per_io_name = {name: len(batches) for name, batches in prefix_data.items()}
nitems = list(nitems_per_io_name.values())[0]
nbatches = list(nbatches_per_io_name.values())[0]
return nitems, nbatches
class BaseDumpWriter(abc.ABC):
FILE_SUFFIX = ".abstract"
def __init__(self, output_dir: Union[str, Path]):
self._output_dir = Path(output_dir)
# outer dict key is prefix (i.e. input/output/labels/...), inner dict key is input/output name
# list is list of batches
self._items_cache: Dict[str, Dict[str, List[np.ndarray]]] = {}
# key is prefix
self._items_counters: Dict[str, int] = {}
self._cache_lock = threading.RLock()
self._flush_threshold_b = FLUSH_THRESHOLD_B
@property
def cache_size(self):
def _get_bytes_size(name, batch):
_validate_batch(name, batch)
if not isinstance(batch, np.ndarray):
batch = np.narray(batch)
return batch.nbytes
with self._cache_lock:
return {
prefix: sum(_get_bytes_size(name, batch) for name, batches in data.items() for batch in batches)
for prefix, data in self._items_cache.items()
}
def _append_to_cache(self, prefix, prefix_data):
if prefix_data is None:
return
if not isinstance(prefix_data, dict):
raise ValueError(f"{prefix} data to store shall be dict")
with self._cache_lock:
cached_prefix_data = self._items_cache.setdefault(prefix, {})
for name, batch in prefix_data.items():
_validate_batch(name, batch)
if not isinstance(batch, np.ndarray):
batch = np.array(batch)
cached_batches = cached_prefix_data.setdefault(name, [])
cached_batches += [batch]
def write(self, **kwargs):
with self._cache_lock:
for prefix, prefix_data in kwargs.items():
self._append_to_cache(prefix, prefix_data)
biggest_prefix_data_size = max(self.cache_size.values())
if biggest_prefix_data_size > self._flush_threshold_b:
self.flush()
def flush(self):
with self._cache_lock:
for prefix, prefix_data in self._items_cache.items():
_validate_prefix_data(prefix_data)
output_path = self._output_dir / self._get_filename(prefix)
self._dump(prefix_data, output_path)
nitems, nbatches = _get_nitems_and_batches(prefix_data)
self._items_counters[prefix] += nitems
self._items_cache = {}
def _get_filename(self, prefix):
idx = self._items_counters.setdefault(prefix, 0)
return f"{prefix}-{idx:012d}{self.FILE_SUFFIX}"
@abc.abstractmethod
def _dump(self, prefix_data: Dict[str, List[np.ndarray]], output_path: Path):
pass
def __enter__(self):
if self._output_dir.exists() and len(list(self._output_dir.iterdir())):
raise ValueError(f"{self._output_dir.as_posix()} is not empty")
self._output_dir.mkdir(parents=True, exist_ok=True)
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.flush()
class PickleDumpWriter(BaseDumpWriter):
FILE_SUFFIX = ".pkl"
def _dump(self, prefix_data: Dict[str, List[np.ndarray]], output_path: Path):
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("wb") as pickle_file:
pickle.dump(prefix_data, pickle_file)
class JsonDumpWriter(BaseDumpWriter):
FILE_SUFFIX = ".json"
def _dump(self, prefix_data: Dict[str, List[np.ndarray]], output_path: Path):
repacked_prefix_data = self._format_data(prefix_data)
output_path.parent.mkdir(parents=True, exist_ok=True)
with output_path.open("w") as json_file:
json.dump(repacked_prefix_data, json_file)
def _format_data(self, prefix_data: Dict[str, List[np.ndarray]]) -> Dict:
def _format_batch_for_perf_analyzer_json_format(batch: np.ndarray):
return {
"content": batch.flatten().tolist(),
"shape": list(batch.shape),
"dtype": str(batch.dtype),
}
_, nbatches = _get_nitems_and_batches(prefix_data)
batches = [{} for _ in range(nbatches)]
for io_name, batches_per_io in prefix_data.items():
for batch_idx, batch in enumerate(batches_per_io):
batches[batch_idx][io_name] = _format_batch_for_perf_analyzer_json_format(batch)
return {"data": batches}
class BaseDumpReader(abc.ABC):
FILE_SUFFIX = ".abstract"
def __init__(self, dump_dir: Union[Path, str]):
self._dump_dir = Path(dump_dir)
def get(self, prefix: str) -> Iterator[Dict[str, np.ndarray]]:
dump_files_paths = sorted(self._dump_dir.glob(f"{prefix}*{self.FILE_SUFFIX}"))
for dump_file_path in dump_files_paths:
prefix_data = self._load_file(dump_file_path)
nitems, nbatches = _get_nitems_and_batches(prefix_data)
for batch_idx in range(nbatches):
yield {io_name: prefix_data[io_name][batch_idx] for io_name in prefix_data}
@abc.abstractmethod
def _load_file(self, dump_file_path: Path) -> Dict[str, List[np.ndarray]]:
pass
def iterate_over(self, prefix_list: List[str]) -> Iterator:
iterators = [self.get(prefix) for prefix in prefix_list]
empty_iterators = [False] * len(iterators)
while not all(empty_iterators):
values = [None] * len(iterators)
for idx, iterator in enumerate(iterators):
if empty_iterators[idx]:
continue
try:
values[idx] = next(iterator)
except StopIteration:
empty_iterators[idx] = True
if all(empty_iterators):
break
if not all(empty_iterators):
yield values
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
pass
class PickleDumpReader(BaseDumpReader):
FILE_SUFFIX = ".pkl"
def _load_file(self, dump_file_path: Path) -> Dict[str, List[np.ndarray]]:
with dump_file_path.open("rb") as pickle_file:
return pickle.load(pickle_file)
class JsonDumpReader(BaseDumpReader):
FILE_SUFFIX = ".json"
def _load_file(self, dump_file_path: Path) -> Dict[str, List[np.ndarray]]:
with dump_file_path.open("rb") as json_file:
data = json.load(json_file)
return self._repack_data(data)
def _repack_data(self, data: Dict) -> Dict[str, List[np.ndarray]]:
result: Dict[str, List[np.ndarray]] = {}
batches = data["data"]
for batch in batches:
for io_name, batch_as_dict in batch.items():
io_batches = result.setdefault(io_name, [])
flat_array = batch_as_dict["content"]
shape = batch_as_dict["shape"]
dtype = batch_as_dict["dtype"]
batch_as_array = np.array(flat_array).reshape(shape).astype(dtype)
io_batches.append(batch_as_array)
return result
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt/tacotron2 | tacotron2 | tacotron2Loader | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TT2I_TACOTRON2LOADER_H
#define TT2I_TACOTRON2LOADER_H
#include "tacotron2Instance.h"
#include <memory>
#include <string>
// forward declaration
namespace nvinfer1
{
class ILogger;
class IBuilder;
} // namespace nvinfer1
namespace tts
{
class EngineCache;
class Tacotron2Loader
{
public:
/**
* @brief Load a new Tacotron2Instance from an engine file or a json file.
*
* @param cache The engine cache.
* @param builder The TensorRT Engine Builder.
* @param filename The name of the engine/json file.
* @param inputLength The maximum length input to support.
* @param fp16 If building an engine from a json file, whether or not to
* allow fp16 operations. If loading an engine file, this input is ignored.
* @param batchSize If building an engine from a json file, the maximum batch
* size to support. If loading an engine file, this input is ignored.
*
* @return The newly created Tacotron2Instance.
*/
static std::shared_ptr<Tacotron2Instance> load(
EngineCache& cache,
nvinfer1::IBuilder& builder,
const std::string& filename,
const int inputLength = 400,
bool fp16 = false,
const int batchSize = 8);
};
} // namespace tts
#endif
|
PyTorch/LanguageModeling/Transformer-XL/pytorch/scripts/tests | tests | train_short | #!/bin/bash
# Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -e
REPO_DIR=${REPO_DIR:-"/workspace/transformer-xl/pytorch/"}
REFERENCE_FILE=$REPO_DIR/scripts/tests/reference_training_throughput
MATH=$1
if [[ ${MATH} != "fp16" && ${MATH} != "fp32" ]]; then
echo "Unsupported option for MATH, use either 'fp16' or 'fp32'"
exit 1
fi
PERF_TOLERANCE=0.9
GPU_NAME=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader |uniq)
echo 'GPU_NAME:' "${GPU_NAME}"
GPU_COUNT=$(nvidia-smi --query-gpu=gpu_name --format=csv,noheader |wc -l)
echo 'GPU_COUNT:' "${GPU_COUNT}"
if (( GPU_COUNT == 16 )); then
SYSTEM=dgx2
else
SYSTEM=dgx1
fi
REFERENCE_PERF=$(grep "${MATH},${GPU_COUNT},${GPU_NAME}" \
${REFERENCE_FILE} | \cut -f 4 -d ',')
if [ -z "${REFERENCE_PERF}" ]; then
echo "WARNING: COULD NOT FIND REFERENCE PERFORMANCE FOR EXECUTED CONFIG"
TARGET_PERF=''
else
PERF_THRESHOLD=$(awk 'BEGIN {print ('"${REFERENCE_PERF}"' * '"${PERF_TOLERANCE}"')}')
TARGET_PERF='--target_throughput '${PERF_THRESHOLD}
fi
cd $REPO_DIR
bash run_wt103_base.sh train "${GPU_COUNT}" \
--config ${SYSTEM}_${GPU_COUNT}gpu_${MATH} \
--debug \
--max_step 5000 \
--max_step_scheduler 40000 \
--target_perplexity 43.5 \
--log_interval 1 \
${TARGET_PERF}
|
TensorFlow2/Recommendation/WideAndDeep/triton/runner | runner | runner | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import pathlib
import signal
import sys
from typing import List, Type
# method from PEP-366 to support relative import in executed modules
if __name__ == "__main__" and __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .config import Config
from .exceptions import RunnerException
from .executor import Executor
from .finalizer import Finalizer
from .logger import LOGGER, log_format
from .maintainer import Maintainer
from .pipeline import Pipeline
from .preparer import Preparer
from .triton import Triton
class Runner:
"""
Runner class. Main entrypoint to performing task and experiments
"""
WORKSPACE = pathlib.Path.cwd()
EXECUTOR_WORKSPACE = WORKSPACE / "runner_workspace"
def __init__(
self,
pipeline: Pipeline,
config: Config,
executor_cls: Type[Executor],
maintainer_cls: Type[Maintainer],
preparer_cls: Type[Preparer],
finalizer_cls: Type[Finalizer],
devices: List[str] = None,
log_level: int = logging.INFO,
):
self._pipeline = pipeline
self._config = config
self._pipeline = pipeline
self._config = config
self._preparer = preparer_cls()
self._finalizer = finalizer_cls()
self._devices = devices or ["0"]
self._log_level = log_level
self._logs_dir = self.EXECUTOR_WORKSPACE / "logs"
self._log_file_path = self._logs_dir / "runner.log"
self._maintainer = maintainer_cls()
self._executor = executor_cls(
workspace=self.EXECUTOR_WORKSPACE,
maintainer=self._maintainer,
pipeline=pipeline,
devices=devices,
)
signal.signal(signal.SIGINT, self._catch)
self._logs_dir.mkdir(parents=True, exist_ok=True)
def start(self) -> None:
"""
Start runner
Returns:
None
"""
self._setup_logger()
task = self._preparer.exec(
workspace=self.EXECUTOR_WORKSPACE,
config=self._config,
pipeline=self._pipeline,
logs_dir=self._logs_dir,
maintainer=self._maintainer,
triton=Triton(),
)
results = []
try:
for result in self._executor.start(task):
results.append(result)
except RunnerException as e:
LOGGER.error(f"Error running task: {str(e)}")
finally:
self._executor.stop()
self._finalizer.exec(workspace=self.EXECUTOR_WORKSPACE, task=task, results=results)
def _catch(self, signum, frame):
"""
SIGINT catcher. Stops executor on any sigterm.
Args:
signum: signal id
frame: signal frame
"""
self._executor.stop()
sys.exit(0)
def _setup_logger(self) -> None:
"""
Add file handle for logger
Returns:
None
"""
file = logging.FileHandler(self._log_file_path)
formatter = logging.Formatter(log_format)
file.setFormatter(formatter)
LOGGER.addHandler(file)
LOGGER.setLevel(level=self._log_level)
LOGGER.initialize(file_path=self._log_file_path)
|
TensorFlow/Detection/SSD/models/research/slim/nets/mobilenet | mobilenet | mobilenet | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Mobilenet Base Class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import contextlib
import copy
import os
import tensorflow as tf
slim = tf.contrib.slim
@slim.add_arg_scope
def apply_activation(x, name=None, activation_fn=None):
return activation_fn(x, name=name) if activation_fn else x
def _fixed_padding(inputs, kernel_size, rate=1):
"""Pads the input along the spatial dimensions independently of input size.
Pads the input such that if it was used in a convolution with 'VALID' padding,
the output would have the same dimensions as if the unpadded input was used
in a convolution with 'SAME' padding.
Args:
inputs: A tensor of size [batch, height_in, width_in, channels].
kernel_size: The kernel to be used in the conv2d or max_pool2d operation.
rate: An integer, rate for atrous convolution.
Returns:
output: A tensor of size [batch, height_out, width_out, channels] with the
input, either intact (if kernel_size == 1) or padded (if kernel_size > 1).
"""
kernel_size_effective = [kernel_size[0] + (kernel_size[0] - 1) * (rate - 1),
kernel_size[0] + (kernel_size[0] - 1) * (rate - 1)]
pad_total = [kernel_size_effective[0] - 1, kernel_size_effective[1] - 1]
pad_beg = [pad_total[0] // 2, pad_total[1] // 2]
pad_end = [pad_total[0] - pad_beg[0], pad_total[1] - pad_beg[1]]
padded_inputs = tf.pad(inputs, [[0, 0], [pad_beg[0], pad_end[0]],
[pad_beg[1], pad_end[1]], [0, 0]])
return padded_inputs
def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
@contextlib.contextmanager
def _set_arg_scope_defaults(defaults):
"""Sets arg scope defaults for all items present in defaults.
Args:
defaults: dictionary/list of pairs, containing a mapping from
function to a dictionary of default args.
Yields:
context manager where all defaults are set.
"""
if hasattr(defaults, 'items'):
items = list(defaults.items())
else:
items = defaults
if not items:
yield
else:
func, default_arg = items[0]
with slim.arg_scope(func, **default_arg):
with _set_arg_scope_defaults(items[1:]):
yield
@slim.add_arg_scope
def depth_multiplier(output_params,
multiplier,
divisible_by=8,
min_depth=8,
**unused_kwargs):
if 'num_outputs' not in output_params:
return
d = output_params['num_outputs']
output_params['num_outputs'] = _make_divisible(d * multiplier, divisible_by,
min_depth)
_Op = collections.namedtuple('Op', ['op', 'params', 'multiplier_func'])
def op(opfunc, **params):
multiplier = params.pop('multiplier_transorm', depth_multiplier)
return _Op(opfunc, params=params, multiplier_func=multiplier)
class NoOpScope(object):
"""No-op context manager."""
def __enter__(self):
return None
def __exit__(self, exc_type, exc_value, traceback):
return False
def safe_arg_scope(funcs, **kwargs):
"""Returns `slim.arg_scope` with all None arguments removed.
Arguments:
funcs: Functions to pass to `arg_scope`.
**kwargs: Arguments to pass to `arg_scope`.
Returns:
arg_scope or No-op context manager.
Note: can be useful if None value should be interpreted as "do not overwrite
this parameter value".
"""
filtered_args = {name: value for name, value in kwargs.items()
if value is not None}
if filtered_args:
return slim.arg_scope(funcs, **filtered_args)
else:
return NoOpScope()
@slim.add_arg_scope
def mobilenet_base( # pylint: disable=invalid-name
inputs,
conv_defs,
multiplier=1.0,
final_endpoint=None,
output_stride=None,
use_explicit_padding=False,
scope=None,
is_training=False):
"""Mobilenet base network.
Constructs a network from inputs to the given final endpoint. By default
the network is constructed in inference mode. To create network
in training mode use:
with slim.arg_scope(mobilenet.training_scope()):
logits, endpoints = mobilenet_base(...)
Args:
inputs: a tensor of shape [batch_size, height, width, channels].
conv_defs: A list of op(...) layers specifying the net architecture.
multiplier: Float multiplier for the depth (number of channels)
for all convolution ops. The value must be greater than zero. Typical
usage will be to set this value in (0, 1) to reduce the number of
parameters or computation cost of the model.
final_endpoint: The name of last layer, for early termination for
for V1-based networks: last layer is "layer_14", for V2: "layer_20"
output_stride: An integer that specifies the requested ratio of input to
output spatial resolution. If not None, then we invoke atrous convolution
if necessary to prevent the network from reducing the spatial resolution
of the activation maps. Allowed values are 1 or any even number, excluding
zero. Typical values are 8 (accurate fully convolutional mode), 16
(fast fully convolutional mode), and 32 (classification mode).
NOTE- output_stride relies on all consequent operators to support dilated
operators via "rate" parameter. This might require wrapping non-conv
operators to operate properly.
use_explicit_padding: Use 'VALID' padding for convolutions, but prepad
inputs so that the output dimensions are the same as if 'SAME' padding
were used.
scope: optional variable scope.
is_training: How to setup batch_norm and other ops. Note: most of the time
this does not need be set directly. Use mobilenet.training_scope() to set
up training instead. This parameter is here for backward compatibility
only. It is safe to set it to the value matching
training_scope(is_training=...). It is also safe to explicitly set
it to False, even if there is outer training_scope set to to training.
(The network will be built in inference mode). If this is set to None,
no arg_scope is added for slim.batch_norm's is_training parameter.
Returns:
tensor_out: output tensor.
end_points: a set of activations for external use, for example summaries or
losses.
Raises:
ValueError: depth_multiplier <= 0, or the target output_stride is not
allowed.
"""
if multiplier <= 0:
raise ValueError('multiplier is not greater than zero.')
# Set conv defs defaults and overrides.
conv_defs_defaults = conv_defs.get('defaults', {})
conv_defs_overrides = conv_defs.get('overrides', {})
if use_explicit_padding:
conv_defs_overrides = copy.deepcopy(conv_defs_overrides)
conv_defs_overrides[
(slim.conv2d, slim.separable_conv2d)] = {'padding': 'VALID'}
if output_stride is not None:
if output_stride == 0 or (output_stride > 1 and output_stride % 2):
raise ValueError('Output stride must be None, 1 or a multiple of 2.')
# a) Set the tensorflow scope
# b) set padding to default: note we might consider removing this
# since it is also set by mobilenet_scope
# c) set all defaults
# d) set all extra overrides.
with _scope_all(scope, default_scope='Mobilenet'), \
safe_arg_scope([slim.batch_norm], is_training=is_training), \
_set_arg_scope_defaults(conv_defs_defaults), \
_set_arg_scope_defaults(conv_defs_overrides):
# The current_stride variable keeps track of the output stride of the
# activations, i.e., the running product of convolution strides up to the
# current network layer. This allows us to invoke atrous convolution
# whenever applying the next convolution would result in the activations
# having output stride larger than the target output_stride.
current_stride = 1
# The atrous convolution rate parameter.
rate = 1
net = inputs
# Insert default parameters before the base scope which includes
# any custom overrides set in mobilenet.
end_points = {}
scopes = {}
for i, opdef in enumerate(conv_defs['spec']):
params = dict(opdef.params)
opdef.multiplier_func(params, multiplier)
stride = params.get('stride', 1)
if output_stride is not None and current_stride == output_stride:
# If we have reached the target output_stride, then we need to employ
# atrous convolution with stride=1 and multiply the atrous rate by the
# current unit's stride for use in subsequent layers.
layer_stride = 1
layer_rate = rate
rate *= stride
else:
layer_stride = stride
layer_rate = 1
current_stride *= stride
# Update params.
params['stride'] = layer_stride
# Only insert rate to params if rate > 1.
if layer_rate > 1:
params['rate'] = layer_rate
# Set padding
if use_explicit_padding:
if 'kernel_size' in params:
net = _fixed_padding(net, params['kernel_size'], layer_rate)
else:
params['use_explicit_padding'] = True
end_point = 'layer_%d' % (i + 1)
try:
net = opdef.op(net, **params)
except Exception:
print('Failed to create op %i: %r params: %r' % (i, opdef, params))
raise
end_points[end_point] = net
scope = os.path.dirname(net.name)
scopes[scope] = end_point
if final_endpoint is not None and end_point == final_endpoint:
break
# Add all tensors that end with 'output' to
# endpoints
for t in net.graph.get_operations():
scope = os.path.dirname(t.name)
bn = os.path.basename(t.name)
if scope in scopes and t.name.endswith('output'):
end_points[scopes[scope] + '/' + bn] = t.outputs[0]
return net, end_points
@contextlib.contextmanager
def _scope_all(scope, default_scope=None):
with tf.variable_scope(scope, default_name=default_scope) as s,\
tf.name_scope(s.original_name_scope):
yield s
@slim.add_arg_scope
def mobilenet(inputs,
num_classes=1001,
prediction_fn=slim.softmax,
reuse=None,
scope='Mobilenet',
base_only=False,
**mobilenet_args):
"""Mobilenet model for classification, supports both V1 and V2.
Note: default mode is inference, use mobilenet.training_scope to create
training network.
Args:
inputs: a tensor of shape [batch_size, height, width, channels].
num_classes: number of predicted classes. If 0 or None, the logits layer
is omitted and the input features to the logits layer (before dropout)
are returned instead.
prediction_fn: a function to get predictions out of logits
(default softmax).
reuse: whether or not the network and its variables should be reused. To be
able to reuse 'scope' must be given.
scope: Optional variable_scope.
base_only: if True will only create the base of the network (no pooling
and no logits).
**mobilenet_args: passed to mobilenet_base verbatim.
- conv_defs: list of conv defs
- multiplier: Float multiplier for the depth (number of channels)
for all convolution ops. The value must be greater than zero. Typical
usage will be to set this value in (0, 1) to reduce the number of
parameters or computation cost of the model.
- output_stride: will ensure that the last layer has at most total stride.
If the architecture calls for more stride than that provided
(e.g. output_stride=16, but the architecture has 5 stride=2 operators),
it will replace output_stride with fractional convolutions using Atrous
Convolutions.
Returns:
logits: the pre-softmax activations, a tensor of size
[batch_size, num_classes]
end_points: a dictionary from components of the network to the corresponding
activation tensor.
Raises:
ValueError: Input rank is invalid.
"""
is_training = mobilenet_args.get('is_training', False)
input_shape = inputs.get_shape().as_list()
if len(input_shape) != 4:
raise ValueError('Expected rank 4 input, was: %d' % len(input_shape))
with tf.variable_scope(scope, 'Mobilenet', reuse=reuse) as scope:
inputs = tf.identity(inputs, 'input')
net, end_points = mobilenet_base(inputs, scope=scope, **mobilenet_args)
if base_only:
return net, end_points
net = tf.identity(net, name='embedding')
with tf.variable_scope('Logits'):
net = global_pool(net)
end_points['global_pool'] = net
if not num_classes:
return net, end_points
net = slim.dropout(net, scope='Dropout', is_training=is_training)
# 1 x 1 x num_classes
# Note: legacy scope name.
logits = slim.conv2d(
net,
num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='Conv2d_1c_1x1')
logits = tf.squeeze(logits, [1, 2])
logits = tf.identity(logits, name='output')
end_points['Logits'] = logits
if prediction_fn:
end_points['Predictions'] = prediction_fn(logits, 'Predictions')
return logits, end_points
def global_pool(input_tensor, pool_op=tf.nn.avg_pool):
"""Applies avg pool to produce 1x1 output.
NOTE: This function is funcitonally equivalenet to reduce_mean, but it has
baked in average pool which has better support across hardware.
Args:
input_tensor: input tensor
pool_op: pooling op (avg pool is default)
Returns:
a tensor batch_size x 1 x 1 x depth.
"""
shape = input_tensor.get_shape().as_list()
if shape[1] is None or shape[2] is None:
kernel_size = tf.convert_to_tensor(
[1, tf.shape(input_tensor)[1],
tf.shape(input_tensor)[2], 1])
else:
kernel_size = [1, shape[1], shape[2], 1]
output = pool_op(
input_tensor, ksize=kernel_size, strides=[1, 1, 1, 1], padding='VALID')
# Recover output shape, for unknown shape.
output.set_shape([None, 1, 1, None])
return output
def training_scope(is_training=True,
weight_decay=0.00004,
stddev=0.09,
dropout_keep_prob=0.8,
bn_decay=0.997):
"""Defines Mobilenet training scope.
Usage:
with tf.contrib.slim.arg_scope(mobilenet.training_scope()):
logits, endpoints = mobilenet_v2.mobilenet(input_tensor)
# the network created will be trainble with dropout/batch norm
# initialized appropriately.
Args:
is_training: if set to False this will ensure that all customizations are
set to non-training mode. This might be helpful for code that is reused
across both training/evaluation, but most of the time training_scope with
value False is not needed. If this is set to None, the parameters is not
added to the batch_norm arg_scope.
weight_decay: The weight decay to use for regularizing the model.
stddev: Standard deviation for initialization, if negative uses xavier.
dropout_keep_prob: dropout keep probability (not set if equals to None).
bn_decay: decay for the batch norm moving averages (not set if equals to
None).
Returns:
An argument scope to use via arg_scope.
"""
# Note: do not introduce parameters that would change the inference
# model here (for example whether to use bias), modify conv_def instead.
batch_norm_params = {
'decay': bn_decay,
'is_training': is_training
}
if stddev < 0:
weight_intitializer = slim.initializers.xavier_initializer()
else:
weight_intitializer = tf.truncated_normal_initializer(stddev=stddev)
# Set weight_decay for weights in Conv and FC layers.
with slim.arg_scope(
[slim.conv2d, slim.fully_connected, slim.separable_conv2d],
weights_initializer=weight_intitializer,
normalizer_fn=slim.batch_norm), \
slim.arg_scope([mobilenet_base, mobilenet], is_training=is_training),\
safe_arg_scope([slim.batch_norm], **batch_norm_params), \
safe_arg_scope([slim.dropout], is_training=is_training,
keep_prob=dropout_keep_prob), \
slim.arg_scope([slim.conv2d], \
weights_regularizer=slim.l2_regularizer(weight_decay)), \
slim.arg_scope([slim.separable_conv2d], weights_regularizer=None) as s:
return s
|
PyTorch/Translation/GNMT/seq2seq/models | models | decoder | # Copyright (c) 2017 Elad Hoffer
# Copyright (c) 2018-2020, NVIDIA CORPORATION. All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import itertools
import torch
import torch.nn as nn
import seq2seq.data.config as config
from seq2seq.models.attention import BahdanauAttention
from seq2seq.utils import init_lstm_
class RecurrentAttention(nn.Module):
"""
LSTM wrapped with an attention module.
"""
def __init__(self, input_size=1024, context_size=1024, hidden_size=1024,
num_layers=1, batch_first=False, dropout=0.2,
init_weight=0.1):
"""
Constructor for the RecurrentAttention.
:param input_size: number of features in input tensor
:param context_size: number of features in output from encoder
:param hidden_size: internal hidden size
:param num_layers: number of layers in LSTM
:param batch_first: if True the model uses (batch,seq,feature) tensors,
if false the model uses (seq, batch, feature)
:param dropout: probability of dropout (on input to LSTM layer)
:param init_weight: range for the uniform initializer
"""
super(RecurrentAttention, self).__init__()
self.rnn = nn.LSTM(input_size, hidden_size, num_layers, bias=True,
batch_first=batch_first)
init_lstm_(self.rnn, init_weight)
self.attn = BahdanauAttention(hidden_size, context_size, context_size,
normalize=True, batch_first=batch_first)
self.dropout = nn.Dropout(dropout)
def forward(self, inputs, hidden, context, context_len):
"""
Execute RecurrentAttention.
:param inputs: tensor with inputs
:param hidden: hidden state for LSTM layer
:param context: context tensor from encoder
:param context_len: vector of encoder sequence lengths
:returns (rnn_outputs, hidden, attn_output, attn_scores)
"""
# set attention mask, sequences have different lengths, this mask
# allows to include only valid elements of context in attention's
# softmax
self.attn.set_mask(context_len, context)
inputs = self.dropout(inputs)
rnn_outputs, hidden = self.rnn(inputs, hidden)
attn_outputs, scores = self.attn(rnn_outputs, context)
return rnn_outputs, hidden, attn_outputs, scores
class Classifier(nn.Module):
"""
Fully-connected classifier
"""
def __init__(self, in_features, out_features, init_weight=0.1):
"""
Constructor for the Classifier.
:param in_features: number of input features
:param out_features: number of output features (size of vocabulary)
:param init_weight: range for the uniform initializer
"""
super(Classifier, self).__init__()
self.classifier = nn.Linear(in_features, out_features)
nn.init.uniform_(self.classifier.weight.data, -init_weight, init_weight)
nn.init.uniform_(self.classifier.bias.data, -init_weight, init_weight)
def forward(self, x):
"""
Execute the classifier.
:param x: output from decoder
"""
out = self.classifier(x)
return out
class ResidualRecurrentDecoder(nn.Module):
"""
Decoder with Embedding, LSTM layers, attention, residual connections and
optinal dropout.
Attention implemented in this module is different than the attention
discussed in the GNMT arxiv paper. In this model the output from the first
LSTM layer of the decoder goes into the attention module, then the
re-weighted context is concatenated with inputs to all subsequent LSTM
layers in the decoder at the current timestep.
Residual connections are enabled after 3rd LSTM layer, dropout is applied
on inputs to LSTM layers.
"""
def __init__(self, vocab_size, hidden_size=1024, num_layers=4, dropout=0.2,
batch_first=False, embedder=None, init_weight=0.1):
"""
Constructor of the ResidualRecurrentDecoder.
:param vocab_size: size of vocabulary
:param hidden_size: hidden size for LSMT layers
:param num_layers: number of LSTM layers
:param dropout: probability of dropout (on input to LSTM layers)
:param batch_first: if True the model uses (batch,seq,feature) tensors,
if false the model uses (seq, batch, feature)
:param embedder: instance of nn.Embedding, if None constructor will
create new embedding layer
:param init_weight: range for the uniform initializer
"""
super(ResidualRecurrentDecoder, self).__init__()
self.num_layers = num_layers
self.att_rnn = RecurrentAttention(hidden_size, hidden_size,
hidden_size, num_layers=1,
batch_first=batch_first,
dropout=dropout)
self.rnn_layers = nn.ModuleList()
for _ in range(num_layers - 1):
self.rnn_layers.append(
nn.LSTM(2 * hidden_size, hidden_size, num_layers=1, bias=True,
batch_first=batch_first))
for lstm in self.rnn_layers:
init_lstm_(lstm, init_weight)
if embedder is not None:
self.embedder = embedder
else:
self.embedder = nn.Embedding(vocab_size, hidden_size,
padding_idx=config.PAD)
nn.init.uniform_(self.embedder.weight.data, -init_weight,
init_weight)
self.classifier = Classifier(hidden_size, vocab_size)
self.dropout = nn.Dropout(p=dropout)
def init_hidden(self, hidden):
"""
Converts flattened hidden state (from sequence generator) into a tuple
of hidden states.
:param hidden: None or flattened hidden state for decoder RNN layers
"""
if hidden is not None:
# per-layer chunks
hidden = hidden.chunk(self.num_layers)
# (h, c) chunks for LSTM layer
hidden = tuple(i.chunk(2) for i in hidden)
else:
hidden = [None] * self.num_layers
self.next_hidden = []
return hidden
def append_hidden(self, h):
"""
Appends the hidden vector h to the list of internal hidden states.
:param h: hidden vector
"""
if self.inference:
self.next_hidden.append(h)
def package_hidden(self):
"""
Flattens the hidden state from all LSTM layers into one tensor (for
the sequence generator).
"""
if self.inference:
hidden = torch.cat(tuple(itertools.chain(*self.next_hidden)))
else:
hidden = None
return hidden
def forward(self, inputs, context, inference=False):
"""
Execute the decoder.
:param inputs: tensor with inputs to the decoder
:param context: state of encoder, encoder sequence lengths and hidden
state of decoder's LSTM layers
:param inference: if True stores and repackages hidden state
"""
self.inference = inference
enc_context, enc_len, hidden = context
hidden = self.init_hidden(hidden)
x = self.embedder(inputs)
x, h, attn, scores = self.att_rnn(x, hidden[0], enc_context, enc_len)
self.append_hidden(h)
x = torch.cat((x, attn), dim=2)
x = self.dropout(x)
x, h = self.rnn_layers[0](x, hidden[1])
self.append_hidden(h)
for i in range(1, len(self.rnn_layers)):
residual = x
x = torch.cat((x, attn), dim=2)
x = self.dropout(x)
x, h = self.rnn_layers[i](x, hidden[i + 1])
self.append_hidden(h)
x = x + residual
x = self.classifier(x)
hidden = self.package_hidden()
return x, scores, [enc_context, enc_len, hidden]
|
JAX/MultiModal/Imagen | Imagen | README | # Imagen on GPUs
Please refer to [Rosetta Imagen](https://github.com/NVIDIA/JAX-Toolbox/tree/main/rosetta/rosetta/projects/imagen), NVIDIA's project that enables seamless training of LLMs, CV models and multimodal models in JAX, for information about running Imagen models and experiments on GPUs.
|
TensorFlow/Detection/SSD/configs | configs | ssd320_full_1gpus | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# SSD with Resnet 50 v1 FPN feature extractor, shared box predictor and focal
# loss (a.k.a Retinanet).
# See Lin et al, https://arxiv.org/abs/1708.02002
# Trained on COCO, initialized from Imagenet classification checkpoint
model {
ssd {
inplace_batchnorm_update: true
freeze_batchnorm: true
num_classes: 90
box_coder {
faster_rcnn_box_coder {
y_scale: 10.0
x_scale: 10.0
height_scale: 5.0
width_scale: 5.0
}
}
matcher {
argmax_matcher {
matched_threshold: 0.5
unmatched_threshold: 0.5
ignore_thresholds: false
negatives_lower_than_unmatched: true
force_match_for_each_row: true
use_matmul_gather: true
}
}
similarity_calculator {
iou_similarity {
}
}
encode_background_as_zeros: true
anchor_generator {
multiscale_anchor_generator {
min_level: 3
max_level: 7
anchor_scale: 4.0
aspect_ratios: [1.0, 2.0, 0.5]
scales_per_octave: 2
}
}
image_resizer {
fixed_shape_resizer {
height: 320
width: 320
}
}
box_predictor {
weight_shared_convolutional_box_predictor {
depth: 256
class_prediction_bias_init: -4.6
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.0004
}
}
initializer {
random_normal_initializer {
stddev: 0.01
mean: 0.0
}
}
batch_norm {
scale: true,
decay: 0.997,
epsilon: 0.001,
}
}
num_layers_before_predictor: 4
kernel_size: 3
}
}
feature_extractor {
type: 'ssd_resnet50_v1_fpn'
fpn {
min_level: 3
max_level: 7
}
min_depth: 16
depth_multiplier: 1.0
conv_hyperparams {
activation: RELU_6,
regularizer {
l2_regularizer {
weight: 0.0004
}
}
initializer {
truncated_normal_initializer {
stddev: 0.03
mean: 0.0
}
}
batch_norm {
scale: true,
decay: 0.997,
epsilon: 0.001,
}
}
override_base_feature_extractor_hyperparams: true
}
loss {
classification_loss {
weighted_sigmoid_focal {
alpha: 0.25
gamma: 2.0
}
}
localization_loss {
weighted_smooth_l1 {
}
}
classification_weight: 1.0
localization_weight: 1.0
}
normalize_loss_by_num_matches: true
normalize_loc_loss_by_codesize: true
post_processing {
batch_non_max_suppression {
score_threshold: 1e-8
iou_threshold: 0.6
max_detections_per_class: 100
max_total_detections: 100
}
score_converter: SIGMOID
}
}
}
train_config: {
fine_tune_checkpoint: "/checkpoints/resnet_v1_50/model.ckpt"
fine_tune_checkpoint_type: "classification"
batch_size: 32
sync_replicas: true
startup_delay_steps: 0
replicas_to_aggregate: 8
num_steps: 100000
data_augmentation_options {
random_horizontal_flip {
}
}
data_augmentation_options {
random_crop_image {
min_object_covered: 0.0
min_aspect_ratio: 0.75
max_aspect_ratio: 3.0
min_area: 0.75
max_area: 1.0
overlap_thresh: 0.0
}
}
optimizer {
momentum_optimizer: {
learning_rate: {
cosine_decay_learning_rate {
learning_rate_base: .02000000000000000000
total_steps: 100000
warmup_learning_rate: .00866640000000000000
warmup_steps: 8000
}
}
momentum_optimizer_value: 0.9
}
use_moving_average: false
}
max_number_of_boxes: 100
unpad_groundtruth_tensors: false
}
train_input_reader: {
tf_record_input_reader {
input_path: "/data/coco2017_tfrecords/*train*"
}
label_map_path: "object_detection/data/mscoco_label_map.pbtxt"
}
eval_config: {
metrics_set: "coco_detection_metrics"
use_moving_averages: false
num_examples: 8000
}
eval_input_reader: {
tf_record_input_reader {
input_path: "/data/coco2017_tfrecords/*val*"
}
label_map_path: "object_detection/data/mscoco_label_map.pbtxt"
shuffle: false
num_readers: 1
}
|
CUDA-Optimized/FastSpeech/fastspeech/dataset | dataset | text_dataset | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the NVIDIA CORPORATION nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import numpy as np
from torch.utils.data import Dataset
from fastspeech.text_norm import text_to_sequence
class TextDataset(Dataset):
def __init__(self, text_list, text_cleaner=['english_cleaners']):
self.texts = text_list
self.text_cleaner = text_cleaner
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = self.texts[idx]
# Text normalization
text_encoded = np.array(text_to_sequence(text, self.text_cleaner))
text_pos = np.array([idx+1 for idx, _ in enumerate(text_encoded)])
data = {
"text": text,
"text_norm": text,
"text_encoded": text_encoded,
"text_pos": text_pos,
}
return data |
TensorFlow/LanguageModeling/BERT | BERT | modeling | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""The main BERT model and related functions."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import copy
import json
import math
import re
import numpy as np
import six
import tensorflow as tf
from gpu_environment import get_custom_getter
class BertConfig(object):
"""Configuration for `BertModel`."""
def __init__(self,
vocab_size,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02):
"""Constructs BertConfig.
Args:
vocab_size: Vocabulary size of `inputs_ids` in `BertModel`.
hidden_size: Size of the encoder layers and the pooler layer.
num_hidden_layers: Number of hidden layers in the Transformer encoder.
num_attention_heads: Number of attention heads for each attention layer in
the Transformer encoder.
intermediate_size: The size of the "intermediate" (i.e., feed-forward)
layer in the Transformer encoder.
hidden_act: The non-linear activation function (function or string) in the
encoder and pooler.
hidden_dropout_prob: The dropout probability for all fully connected
layers in the embeddings, encoder, and pooler.
attention_probs_dropout_prob: The dropout ratio for the attention
probabilities.
max_position_embeddings: The maximum sequence length that this model might
ever be used with. Typically set this to something large just in case
(e.g., 512 or 1024 or 2048).
type_vocab_size: The vocabulary size of the `token_type_ids` passed into
`BertModel`.
initializer_range: The stdev of the truncated_normal_initializer for
initializing all weight matrices.
"""
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.hidden_act = hidden_act
self.intermediate_size = intermediate_size
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
@classmethod
def from_dict(cls, json_object):
"""Constructs a `BertConfig` from a Python dictionary of parameters."""
config = BertConfig(vocab_size=None)
for (key, value) in six.iteritems(json_object):
config.__dict__[key] = value
return config
@classmethod
def from_json_file(cls, json_file):
"""Constructs a `BertConfig` from a json file of parameters."""
with tf.io.gfile.GFile(json_file, "r") as reader:
text = reader.read()
return cls.from_dict(json.loads(text))
def to_dict(self):
"""Serializes this instance to a Python dictionary."""
output = copy.deepcopy(self.__dict__)
return output
def to_json_string(self):
"""Serializes this instance to a JSON string."""
return json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n"
class BertModel(object):
"""BERT model ("Bidirectional Encoder Representations from Transformers").
Example usage:
```python
# Already been converted into WordPiece token ids
input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])
input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])
token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])
config = modeling.BertConfig(vocab_size=32000, hidden_size=512,
num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)
model = modeling.BertModel(config=config, is_training=True,
input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)
label_embeddings = tf.get_variable(...)
pooled_output = model.get_pooled_output()
logits = tf.matmul(pooled_output, label_embeddings)
...
```
"""
def __init__(self,
config,
is_training,
input_ids,
input_mask=None,
token_type_ids=None,
use_one_hot_embeddings=False,
scope=None,
compute_type=tf.float32):
"""Constructor for BertModel.
Args:
config: `BertConfig` instance.
is_training: bool. true for training model, false for eval model. Controls
whether dropout will be applied.
input_ids: int32 Tensor of shape [batch_size, seq_length].
input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
embeddings or tf.embedding_lookup() for the word embeddings. On the TPU,
it is much faster if this is True, on the CPU or GPU, it is faster if
this is False.
scope: (optional) variable scope. Defaults to "bert".
compute_type: (optional) either float32 or float16. Only applies to GPUs.
Raises:
ValueError: The config is invalid or one of the input tensor shapes
is invalid.
"""
config = copy.deepcopy(config)
if not is_training:
config.hidden_dropout_prob = 0.0
config.attention_probs_dropout_prob = 0.0
input_shape = get_shape_list(input_ids, expected_rank=2)
batch_size = input_shape[0]
seq_length = input_shape[1]
if input_mask is None:
input_mask = tf.ones(shape=[batch_size, seq_length], dtype=tf.int32)
if token_type_ids is None:
token_type_ids = tf.zeros(shape=[batch_size, seq_length], dtype=tf.int32)
with tf.variable_scope(scope, default_name="bert", custom_getter=get_custom_getter(compute_type)):
with tf.variable_scope("embeddings"):
# For good convergence with mixed precision training,
# it is important that the embedding codes remain fp32.
# Perform embedding lookup on the word ids.
(self.embedding_output, self.embedding_table) = embedding_lookup(
input_ids=input_ids,
vocab_size=config.vocab_size,
embedding_size=config.hidden_size,
initializer_range=config.initializer_range,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=use_one_hot_embeddings)
# Add positional embeddings and token type embeddings, then layer
# normalize and perform dropout.
self.embedding_output = embedding_postprocessor(
input_tensor=self.embedding_output,
use_token_type=True,
token_type_ids=token_type_ids,
token_type_vocab_size=config.type_vocab_size,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=config.initializer_range,
max_position_embeddings=config.max_position_embeddings,
dropout_prob=config.hidden_dropout_prob,
use_one_hot_embeddings=use_one_hot_embeddings)
with tf.variable_scope("encoder"):
# This converts a 2D mask of shape [batch_size, seq_length] to a 3D
# mask of shape [batch_size, seq_length, seq_length] which is used
# for the attention scores.
attention_mask = create_attention_mask_from_input_mask(
input_ids, input_mask)
# Run the stacked transformer.
# `sequence_output` shape = [batch_size, seq_length, hidden_size].
self.all_encoder_layers = transformer_model(
input_tensor=tf.saturate_cast(self.embedding_output, compute_type),
attention_mask=attention_mask,
hidden_size=config.hidden_size,
num_hidden_layers=config.num_hidden_layers,
num_attention_heads=config.num_attention_heads,
intermediate_size=config.intermediate_size,
intermediate_act_fn=get_activation(config.hidden_act),
hidden_dropout_prob=config.hidden_dropout_prob,
attention_probs_dropout_prob=config.attention_probs_dropout_prob,
initializer_range=config.initializer_range,
do_return_all_layers=True)
self.sequence_output = tf.cast(self.all_encoder_layers[-1], tf.float32)
# The "pooler" converts the encoded sequence tensor of shape
# [batch_size, seq_length, hidden_size] to a tensor of shape
# [batch_size, hidden_size]. This is necessary for segment-level
# (or segment-pair-level) classification tasks where we need a fixed
# dimensional representation of the segment.
with tf.variable_scope("pooler"):
# We "pool" the model by simply taking the hidden state corresponding
# to the first token. We assume that this has been pre-trained
first_token_tensor = tf.squeeze(self.sequence_output[:, 0:1, :], axis=1)
self.pooled_output = tf.layers.dense(
first_token_tensor,
config.hidden_size,
activation=tf.tanh,
kernel_initializer=create_initializer(config.initializer_range))
def get_pooled_output(self):
return self.pooled_output
def get_sequence_output(self):
"""Gets final hidden layer of encoder.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the final hidden of the transformer encoder.
"""
return self.sequence_output
def get_all_encoder_layers(self):
return self.all_encoder_layers
def get_embedding_output(self):
"""Gets output of the embedding lookup (i.e., input to the transformer).
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size] corresponding
to the output of the embedding layer, after summing the word
embeddings with the positional embeddings and the token type embeddings,
then performing layer normalization. This is the input to the transformer.
"""
return self.embedding_output
def get_embedding_table(self):
return self.embedding_table
def gelu(x):
"""Gaussian Error Linear Unit.
This is a smoother version of the RELU.
Original paper: https://arxiv.org/abs/1606.08415
Args:
x: float Tensor to perform activation.
Returns:
`x` with the GELU activation applied.
"""
cdf = 0.5 * (1.0 + tf.tanh(
(np.sqrt(2 / np.pi) * (x + 0.044715 * tf.pow(x, 3)))))
return x * cdf
def get_activation(activation_string):
"""Maps a string to a Python function, e.g., "relu" => `tf.nn.relu`.
Args:
activation_string: String name of the activation function.
Returns:
A Python function corresponding to the activation function. If
`activation_string` is None, empty, or "linear", this will return None.
If `activation_string` is not a string, it will return `activation_string`.
Raises:
ValueError: The `activation_string` does not correspond to a known
activation.
"""
# We assume that anything that"s not a string is already an activation
# function, so we just return it.
if not isinstance(activation_string, six.string_types):
return activation_string
if not activation_string:
return None
act = activation_string.lower()
if act == "linear":
return None
elif act == "relu":
return tf.nn.relu
elif act == "gelu":
return gelu
elif act == "tanh":
return tf.tanh
else:
raise ValueError("Unsupported activation: %s" % act)
def get_assignment_map_from_checkpoint(tvars, init_checkpoint):
"""Compute the union of the current variables and checkpoint variables."""
assignment_map = {}
initialized_variable_names = {}
name_to_variable = collections.OrderedDict()
for var in tvars:
name = var.name
m = re.match("^(.*):\\d+$", name)
if m is not None:
name = m.group(1)
name_to_variable[name] = var
init_vars = tf.train.list_variables(init_checkpoint)
assignment_map = collections.OrderedDict()
for x in init_vars:
(name, var) = (x[0], x[1])
if name not in name_to_variable:
continue
assignment_map[name] = name
initialized_variable_names[name] = 1
initialized_variable_names[name + ":0"] = 1
return (assignment_map, initialized_variable_names)
def dropout(input_tensor, dropout_prob):
"""Perform dropout.
Args:
input_tensor: float Tensor.
dropout_prob: Python float. The probability of dropping out a value (NOT of
*keeping* a dimension as in `tf.nn.dropout`).
Returns:
A version of `input_tensor` with dropout applied.
"""
if dropout_prob is None or dropout_prob == 0.0:
return input_tensor
output = tf.nn.dropout(input_tensor, 1.0 - dropout_prob)
return output
def layer_norm(input_tensor, name=None):
"""Run layer normalization on the last dimension of the tensor."""
if input_tensor.dtype == tf.float16:
try:
from fused_layer_norm import fused_layer_norm
return fused_layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name,
use_fused_batch_norm=True)
except ImportError:
return tf.contrib.layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
else:
return tf.contrib.layers.layer_norm(
inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)
def layer_norm_and_dropout(input_tensor, dropout_prob, name=None):
"""Runs layer normalization followed by dropout."""
output_tensor = layer_norm(input_tensor, name)
output_tensor = dropout(output_tensor, dropout_prob)
return output_tensor
def create_initializer(initializer_range=0.02):
"""Creates a `truncated_normal_initializer` with the given range."""
return tf.truncated_normal_initializer(stddev=initializer_range)
def embedding_lookup(input_ids,
vocab_size,
embedding_size=128,
initializer_range=0.02,
word_embedding_name="word_embeddings",
use_one_hot_embeddings=False):
"""Looks up words embeddings for id tensor.
Args:
input_ids: int32 Tensor of shape [batch_size, seq_length] containing word
ids.
vocab_size: int. Size of the embedding vocabulary.
embedding_size: int. Width of the word embeddings.
initializer_range: float. Embedding initialization range.
word_embedding_name: string. Name of the embedding table.
use_one_hot_embeddings: bool. If True, use one-hot method for word
embeddings. If False, use `tf.gather()`.
Returns:
float Tensor of shape [batch_size, seq_length, embedding_size].
"""
# This function assumes that the input is of shape [batch_size, seq_length,
# num_inputs].
#
# If the input is a 2D tensor of shape [batch_size, seq_length], we
# reshape to [batch_size, seq_length, 1].
if input_ids.shape.ndims == 2:
input_ids = tf.expand_dims(input_ids, axis=[-1])
embedding_table = tf.get_variable(
name=word_embedding_name,
shape=[vocab_size, embedding_size],
initializer=create_initializer(initializer_range))
flat_input_ids = tf.reshape(input_ids, [-1])
if use_one_hot_embeddings:
one_hot_input_ids = tf.one_hot(flat_input_ids, depth=vocab_size)
output = tf.matmul(one_hot_input_ids, embedding_table)
else:
output = tf.gather(embedding_table, flat_input_ids)
input_shape = get_shape_list(input_ids)
output = tf.reshape(output,
input_shape[0:-1] + [input_shape[-1] * embedding_size])
return (output, embedding_table)
def embedding_postprocessor(input_tensor,
use_token_type=False,
token_type_ids=None,
token_type_vocab_size=16,
token_type_embedding_name="token_type_embeddings",
use_position_embeddings=True,
position_embedding_name="position_embeddings",
initializer_range=0.02,
max_position_embeddings=512,
dropout_prob=0.1,
use_one_hot_embeddings=False):
"""Performs various post-processing on a word embedding tensor.
Args:
input_tensor: float Tensor of shape [batch_size, seq_length,
embedding_size].
use_token_type: bool. Whether to add embeddings for `token_type_ids`.
token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].
Must be specified if `use_token_type` is True.
token_type_vocab_size: int. The vocabulary size of `token_type_ids`.
token_type_embedding_name: string. The name of the embedding table variable
for token type ids.
use_position_embeddings: bool. Whether to add position embeddings for the
position of each token in the sequence.
position_embedding_name: string. The name of the embedding table variable
for positional embeddings.
initializer_range: float. Range of the weight initialization.
max_position_embeddings: int. Maximum sequence length that might ever be
used with this model. This can be longer than the sequence length of
input_tensor, but cannot be shorter.
dropout_prob: float. Dropout probability applied to the final output tensor.
use_one_hot_embeddings: (optional) bool. Whether to use one-hot word
embeddings or tf.embedding_lookup() for the word embeddings.
Returns:
float tensor with same shape as `input_tensor`.
Raises:
ValueError: One of the tensor shapes or input values is invalid.
"""
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
width = input_shape[2]
output = input_tensor
if use_token_type:
if token_type_ids is None:
raise ValueError("`token_type_ids` must be specified if"
"`use_token_type` is True.")
token_type_table = tf.get_variable(
name=token_type_embedding_name,
shape=[token_type_vocab_size, width],
initializer=create_initializer(initializer_range))
flat_token_type_ids = tf.reshape(token_type_ids, [-1])
if use_one_hot_embeddings:
# This vocab will be small so we always do one-hot here, since it is
# always faster for a small vocabulary.
one_hot_ids = tf.one_hot(flat_token_type_ids, depth=token_type_vocab_size)
token_type_embeddings = tf.matmul(one_hot_ids, token_type_table)
else:
token_type_embeddings = tf.gather(token_type_table, flat_token_type_ids)
token_type_embeddings = tf.reshape(token_type_embeddings,
[batch_size, seq_length, width])
output += token_type_embeddings
if use_position_embeddings:
full_position_embeddings = tf.get_variable(
name=position_embedding_name,
shape=[max_position_embeddings, width],
initializer=create_initializer(initializer_range))
# Since the position embedding table is a learned variable, we create it
# using a (long) sequence length `max_position_embeddings`. The actual
# sequence length might be shorter than this, for faster training of
# tasks that do not have long sequences.
#
# So `full_position_embeddings` is effectively an embedding table
# for position [0, 1, 2, ..., max_position_embeddings-1], and the current
# sequence has positions [0, 1, 2, ... seq_length-1], so we can just
# perform a slice.
position_embeddings = tf.slice(full_position_embeddings, [0, 0],
[seq_length, width])
num_dims = len(output.shape.as_list())
# Only the last two dimensions are relevant (`seq_length` and `width`), so
# we broadcast among the first dimensions, which is typically just
# the batch size.
position_broadcast_shape = []
for _ in range(num_dims - 2):
position_broadcast_shape.append(1)
position_broadcast_shape.extend([seq_length, width])
position_embeddings = tf.reshape(position_embeddings,
position_broadcast_shape)
output += position_embeddings
output = layer_norm_and_dropout(output, dropout_prob)
return output
def create_attention_mask_from_input_mask(from_tensor, to_mask):
"""Create 3D attention mask from a 2D tensor mask.
Args:
from_tensor: 2D or 3D Tensor of shape [batch_size, from_seq_length, ...].
to_mask: int32 Tensor of shape [batch_size, to_seq_length].
Returns:
float Tensor of shape [batch_size, from_seq_length, to_seq_length].
"""
to_mask = tf.cast(to_mask, dtype=tf.float32)
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
batch_size = from_shape[0]
to_shape = get_shape_list(to_mask, expected_rank=2)
to_seq_length = to_shape[1]
to_mask = tf.reshape(to_mask, [batch_size, 1, to_seq_length])
# The mask will be automatically broadcasted to
# [batch_size, from_seq_length, to_seq_length] when it is used in the
# attention layer.
return to_mask
def attention_layer(from_tensor,
to_tensor,
attention_mask=None,
num_attention_heads=1,
size_per_head=512,
query_act=None,
key_act=None,
value_act=None,
attention_probs_dropout_prob=0.0,
initializer_range=0.02,
do_return_2d_tensor=False,
batch_size=None,
from_seq_length=None,
to_seq_length=None):
"""Performs multi-headed attention from `from_tensor` to `to_tensor`.
This is an implementation of multi-headed attention based on "Attention
is all you Need". If `from_tensor` and `to_tensor` are the same, then
this is self-attention. Each timestep in `from_tensor` attends to the
corresponding sequence in `to_tensor`, and returns a fixed-with vector.
This function first projects `from_tensor` into a "query" tensor and
`to_tensor` into "key" and "value" tensors. These are (effectively) a list
of tensors of length `num_attention_heads`, where each tensor is of shape
[batch_size, seq_length, size_per_head].
Then, the query and key tensors are dot-producted and scaled. These are
softmaxed to obtain attention probabilities. The value tensors are then
interpolated by these probabilities, then concatenated back to a single
tensor and returned.
In practice, the multi-headed attention are done with transposes and
reshapes rather than actual separate tensors.
Args:
from_tensor: float Tensor of shape [batch_size, from_seq_length,
from_width].
to_tensor: float Tensor of shape [batch_size, to_seq_length, to_width].
attention_mask: (optional) int32 Tensor of shape [batch_size,
from_seq_length, to_seq_length]. The values should be 1 or 0. The
attention scores will effectively be set to -infinity for any positions in
the mask that are 0, and will be unchanged for positions that are 1.
num_attention_heads: int. Number of attention heads.
size_per_head: int. Size of each attention head.
query_act: (optional) Activation function for the query transform.
key_act: (optional) Activation function for the key transform.
value_act: (optional) Activation function for the value transform.
attention_probs_dropout_prob: (optional) float. Dropout probability of the
attention probabilities.
initializer_range: float. Range of the weight initializer.
do_return_2d_tensor: bool. If True, the output will be of shape [batch_size
* from_seq_length, num_attention_heads * size_per_head]. If False, the
output will be of shape [batch_size, from_seq_length, num_attention_heads
* size_per_head].
batch_size: (Optional) int. If the input is 2D, this might be the batch size
of the 3D version of the `from_tensor` and `to_tensor`.
from_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `from_tensor`.
to_seq_length: (Optional) If the input is 2D, this might be the seq length
of the 3D version of the `to_tensor`.
Returns:
float Tensor of shape [batch_size, from_seq_length,
num_attention_heads * size_per_head]. (If `do_return_2d_tensor` is
true, this will be of shape [batch_size * from_seq_length,
num_attention_heads * size_per_head]).
Raises:
ValueError: Any of the arguments or tensor shapes are invalid.
"""
def transpose_for_scores(input_tensor, batch_size, num_attention_heads,
seq_length, width):
output_tensor = tf.reshape(
input_tensor, [batch_size, seq_length, num_attention_heads, width])
output_tensor = tf.transpose(output_tensor, [0, 2, 1, 3])
return output_tensor
from_shape = get_shape_list(from_tensor, expected_rank=[2, 3])
to_shape = get_shape_list(to_tensor, expected_rank=[2, 3])
if len(from_shape) != len(to_shape):
raise ValueError(
"The rank of `from_tensor` must match the rank of `to_tensor`.")
if len(from_shape) == 3:
batch_size = from_shape[0]
from_seq_length = from_shape[1]
to_seq_length = to_shape[1]
elif len(from_shape) == 2:
if (batch_size is None or from_seq_length is None or to_seq_length is None):
raise ValueError(
"When passing in rank 2 tensors to attention_layer, the values "
"for `batch_size`, `from_seq_length`, and `to_seq_length` "
"must all be specified.")
# Scalar dimensions referenced here:
# B = batch size (number of sequences)
# F = `from_tensor` sequence length
# T = `to_tensor` sequence length
# N = `num_attention_heads`
# H = `size_per_head`
from_tensor_2d = reshape_to_matrix(from_tensor)
to_tensor_2d = reshape_to_matrix(to_tensor)
# `query_layer` = [B*F, N*H]
query_layer = tf.layers.dense(
from_tensor_2d,
num_attention_heads * size_per_head,
activation=query_act,
name="query",
kernel_initializer=create_initializer(initializer_range))
# `key_layer` = [B*T, N*H]
key_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=key_act,
name="key",
kernel_initializer=create_initializer(initializer_range))
# `value_layer` = [B*T, N*H]
value_layer = tf.layers.dense(
to_tensor_2d,
num_attention_heads * size_per_head,
activation=value_act,
name="value",
kernel_initializer=create_initializer(initializer_range))
# `query_layer` = [B, N, F, H]
query_layer = transpose_for_scores(query_layer, batch_size,
num_attention_heads, from_seq_length,
size_per_head)
# `key_layer` = [B, N, T, H]
key_layer = transpose_for_scores(key_layer, batch_size, num_attention_heads,
to_seq_length, size_per_head)
# Take the dot product between "query" and "key" to get the raw
# attention scores.
# `attention_scores` = [B, N, F, T]
attention_scores = tf.matmul(query_layer, key_layer, transpose_b=True)
attention_scores = tf.multiply(attention_scores,
1.0 / math.sqrt(float(size_per_head)))
if attention_mask is not None:
# `attention_mask` = [B, 1, F, T]
attention_mask = tf.expand_dims(attention_mask, axis=[1])
# Since attention_mask is 1.0 for positions we want to attend and 0.0 for
# masked positions, this operation will create a tensor which is 0.0 for
# positions we want to attend and -10000.0 for masked positions.
adder = (1.0 - tf.cast(attention_mask, attention_scores.dtype)) * -10000.0
# Since we are adding it to the raw scores before the softmax, this is
# effectively the same as removing these entirely.
attention_scores += adder
# Normalize the attention scores to probabilities.
# `attention_probs` = [B, N, F, T]
attention_probs = tf.nn.softmax(attention_scores)
# This is actually dropping out entire tokens to attend to, which might
# seem a bit unusual, but is taken from the original Transformer paper.
attention_probs = dropout(attention_probs, attention_probs_dropout_prob)
# `value_layer` = [B, T, N, H]
value_layer = tf.reshape(
value_layer,
[batch_size, to_seq_length, num_attention_heads, size_per_head])
# `value_layer` = [B, N, T, H]
value_layer = tf.transpose(value_layer, [0, 2, 1, 3])
# `context_layer` = [B, N, F, H]
context_layer = tf.matmul(attention_probs, value_layer)
# `context_layer` = [B, F, N, H]
context_layer = tf.transpose(context_layer, [0, 2, 1, 3])
if do_return_2d_tensor:
# `context_layer` = [B*F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size * from_seq_length, num_attention_heads * size_per_head])
else:
# `context_layer` = [B, F, N*H]
context_layer = tf.reshape(
context_layer,
[batch_size, from_seq_length, num_attention_heads * size_per_head])
return context_layer
def transformer_model(input_tensor,
attention_mask=None,
hidden_size=768,
num_hidden_layers=12,
num_attention_heads=12,
intermediate_size=3072,
intermediate_act_fn=gelu,
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
initializer_range=0.02,
do_return_all_layers=False):
"""Multi-headed, multi-layer Transformer from "Attention is All You Need".
This is almost an exact implementation of the original Transformer encoder.
See the original paper:
https://arxiv.org/abs/1706.03762
Also see:
https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/models/transformer.py
Args:
input_tensor: float Tensor of shape [batch_size, seq_length, hidden_size].
attention_mask: (optional) int32 Tensor of shape [batch_size, seq_length,
seq_length], with 1 for positions that can be attended to and 0 in
positions that should not be.
hidden_size: int. Hidden size of the Transformer.
num_hidden_layers: int. Number of layers (blocks) in the Transformer.
num_attention_heads: int. Number of attention heads in the Transformer.
intermediate_size: int. The size of the "intermediate" (a.k.a., feed
forward) layer.
intermediate_act_fn: function. The non-linear activation function to apply
to the output of the intermediate/feed-forward layer.
hidden_dropout_prob: float. Dropout probability for the hidden layers.
attention_probs_dropout_prob: float. Dropout probability of the attention
probabilities.
initializer_range: float. Range of the initializer (stddev of truncated
normal).
do_return_all_layers: Whether to also return all layers or just the final
layer.
Returns:
float Tensor of shape [batch_size, seq_length, hidden_size], the final
hidden layer of the Transformer.
Raises:
ValueError: A Tensor shape or parameter is invalid.
"""
if hidden_size % num_attention_heads != 0:
raise ValueError(
"The hidden size (%d) is not a multiple of the number of attention "
"heads (%d)" % (hidden_size, num_attention_heads))
attention_head_size = int(hidden_size / num_attention_heads)
input_shape = get_shape_list(input_tensor, expected_rank=3)
batch_size = input_shape[0]
seq_length = input_shape[1]
input_width = input_shape[2]
# The Transformer performs sum residuals on all layers so the input needs
# to be the same as the hidden size.
if input_width != hidden_size:
raise ValueError("The width of the input tensor (%d) != hidden size (%d)" %
(input_width, hidden_size))
# We keep the representation as a 2D tensor to avoid re-shaping it back and
# forth from a 3D tensor to a 2D tensor. Re-shapes are normally free on
# the GPU/CPU but may not be free on the TPU, so we want to minimize them to
# help the optimizer.
prev_output = reshape_to_matrix(input_tensor)
all_layer_outputs = []
for layer_idx in range(num_hidden_layers):
with tf.variable_scope("layer_%d" % layer_idx):
layer_input = prev_output
with tf.variable_scope("attention"):
attention_heads = []
with tf.variable_scope("self"):
attention_head = attention_layer(
from_tensor=layer_input,
to_tensor=layer_input,
attention_mask=attention_mask,
num_attention_heads=num_attention_heads,
size_per_head=attention_head_size,
attention_probs_dropout_prob=attention_probs_dropout_prob,
initializer_range=initializer_range,
do_return_2d_tensor=True,
batch_size=batch_size,
from_seq_length=seq_length,
to_seq_length=seq_length)
attention_heads.append(attention_head)
attention_output = None
if len(attention_heads) == 1:
attention_output = attention_heads[0]
else:
# In the case where we have other sequences, we just concatenate
# them to the self-attention head before the projection.
attention_output = tf.concat(attention_heads, axis=-1)
# Run a linear projection of `hidden_size` then add a residual
# with `layer_input`.
with tf.variable_scope("output"):
attention_output = tf.layers.dense(
attention_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
attention_output = dropout(attention_output, hidden_dropout_prob)
attention_output = layer_norm(attention_output + layer_input)
# The activation is only applied to the "intermediate" hidden layer.
with tf.variable_scope("intermediate"):
intermediate_output = tf.layers.dense(
attention_output,
intermediate_size,
activation=intermediate_act_fn,
kernel_initializer=create_initializer(initializer_range))
# Down-project back to `hidden_size` then add the residual.
with tf.variable_scope("output"):
layer_output = tf.layers.dense(
intermediate_output,
hidden_size,
kernel_initializer=create_initializer(initializer_range))
layer_output = dropout(layer_output, hidden_dropout_prob)
layer_output = layer_norm(layer_output + attention_output)
prev_output = layer_output
all_layer_outputs.append(layer_output)
if do_return_all_layers:
final_outputs = []
for layer_output in all_layer_outputs:
final_output = reshape_from_matrix(layer_output, input_shape)
final_outputs.append(final_output)
return final_outputs
else:
final_output = reshape_from_matrix(prev_output, input_shape)
return final_output
def get_shape_list(tensor, expected_rank=None, name=None):
"""Returns a list of the shape of tensor, preferring static dimensions.
Args:
tensor: A tf.Tensor object to find the shape of.
expected_rank: (optional) int. The expected rank of `tensor`. If this is
specified and the `tensor` has a different rank, and exception will be
thrown.
name: Optional name of the tensor for the error message.
Returns:
A list of dimensions of the shape of tensor. All static dimensions will
be returned as python integers, and dynamic dimensions will be returned
as tf.Tensor scalars.
"""
if name is None:
name = tensor.name
if expected_rank is not None:
assert_rank(tensor, expected_rank, name)
shape = tensor.shape.as_list()
non_static_indexes = []
for (index, dim) in enumerate(shape):
if dim is None:
non_static_indexes.append(index)
if not non_static_indexes:
return shape
dyn_shape = tf.shape(tensor)
for index in non_static_indexes:
shape[index] = dyn_shape[index]
return shape
def reshape_to_matrix(input_tensor):
"""Reshapes a >= rank 2 tensor to a rank 2 tensor (i.e., a matrix)."""
ndims = input_tensor.shape.ndims
if ndims < 2:
raise ValueError("Input tensor must have at least rank 2. Shape = %s" %
(input_tensor.shape))
if ndims == 2:
return input_tensor
width = input_tensor.shape[-1]
output_tensor = tf.reshape(input_tensor, [-1, width])
return output_tensor
def reshape_from_matrix(output_tensor, orig_shape_list):
"""Reshapes a rank 2 tensor back to its original rank >= 2 tensor."""
if len(orig_shape_list) == 2:
return output_tensor
output_shape = get_shape_list(output_tensor)
orig_dims = orig_shape_list[0:-1]
width = output_shape[-1]
return tf.reshape(output_tensor, orig_dims + [width])
def assert_rank(tensor, expected_rank, name=None):
"""Raises an exception if the tensor rank is not of the expected rank.
Args:
tensor: A tf.Tensor to check the rank of.
expected_rank: Python integer or list of integers, expected rank.
name: Optional name of the tensor for the error message.
Raises:
ValueError: If the expected shape doesn't match the actual shape.
"""
if name is None:
name = tensor.name
expected_rank_dict = {}
if isinstance(expected_rank, six.integer_types):
expected_rank_dict[expected_rank] = True
else:
for x in expected_rank:
expected_rank_dict[x] = True
actual_rank = tensor.shape.ndims
if actual_rank not in expected_rank_dict:
scope_name = tf.get_variable_scope().name
raise ValueError(
"For the tensor `%s` in scope `%s`, the actual rank "
"`%d` (shape = %s) is not equal to the expected rank `%s`" %
(name, scope_name, actual_rank, str(tensor.shape), str(expected_rank)))
|
PyTorch/Segmentation/MaskRCNN/pytorch/maskrcnn_benchmark/solver | solver | __init__ | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
from .build import make_optimizer
from .build import make_lr_scheduler
from .lr_scheduler import WarmupMultiStepLR
|
PyTorch/DrugDiscovery/MoFlow/moflow/runtime | runtime | evaluate | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from functools import partial
import os
import numpy as np
import torch
from torch.cuda.amp import autocast
from moflow.config import CONFIGS
from moflow.data import transform
from moflow.data.data_loader import NumpyTupleDataset
from moflow.model.model import MoFlow
from moflow.utils import check_validity, convert_predictions_to_mols, predictions_to_smiles, check_novelty
from moflow.runtime.arguments import PARSER
from moflow.runtime.common import get_newest_checkpoint, load_state
from moflow.runtime.distributed_utils import get_device
from moflow.runtime.generate import infer
from moflow.runtime.logger import MetricsLogger, setup_logging
if __name__ == '__main__':
from rdkit import RDLogger
RDLogger.DisableLog('rdApp.*')
args = PARSER.parse_args()
logger = setup_logging(args)
snapshot_path = get_newest_checkpoint(args.results_dir)
config = CONFIGS[args.config_name]
model = MoFlow(config)
device = get_device(args.local_rank)
if snapshot_path is not None:
epoch, ln_var = load_state(snapshot_path, model, device=device)
elif args.allow_untrained:
epoch, ln_var = 0, 0
else:
raise RuntimeError('Generating molecules from an untrained network! '
'If this was intentional, pass --allow_untrained flag.')
model.to(device)
model.eval()
if args.steps == -1:
args.steps = 1
acc_logger = MetricsLogger(logger)
valid_idx = transform.get_val_ids(config, args.data_dir)
dataset = NumpyTupleDataset.load(
os.path.join(args.data_dir, config.dataset_config.dataset_file),
transform=partial(transform.transform_fn, config=config),
)
train_idx = [t for t in range(len(dataset)) if t not in valid_idx]
n_train = len(train_idx)
train_dataset = torch.utils.data.Subset(dataset, train_idx)
train_x = torch.Tensor(np.array([a[0] for a in train_dataset]))
train_adj = torch.Tensor(np.array([a[1] for a in train_dataset]))
train_smiles = set(predictions_to_smiles(train_adj, train_x, config))
with autocast(enabled=args.amp):
for i in range(args.steps):
results = infer(
model, config, ln_var=ln_var, temp=args.temperature, batch_size=args.batch_size,
device=device)
mols_batch = convert_predictions_to_mols(*results, correct_validity=args.correct_validity)
validity_info = check_validity(mols_batch)
novel_r, abs_novel_r = check_novelty(validity_info['valid_smiles'], train_smiles, len(mols_batch))
_, nuv = check_novelty(list(set(validity_info['valid_smiles'])), train_smiles, len(mols_batch))
metrics = {
'validity': validity_info['valid_ratio'],
'novelty': novel_r,
'uniqueness': validity_info['unique_ratio'],
'abs_novelty': abs_novel_r,
'abs_uniqueness': validity_info['abs_unique_ratio'],
'nuv': nuv,
}
acc_logger.update(metrics)
acc_logger.summarize(step=tuple())
|
TensorFlow/Detection/SSD/models/research/slim/nets/nasnet | nasnet | nasnet | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Contains the definition for the NASNet classification networks.
Paper: https://arxiv.org/abs/1707.07012
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import tensorflow as tf
from nets.nasnet import nasnet_utils
arg_scope = tf.contrib.framework.arg_scope
slim = tf.contrib.slim
# Notes for training NASNet Cifar Model
# -------------------------------------
# batch_size: 32
# learning rate: 0.025
# cosine (single period) learning rate decay
# auxiliary head loss weighting: 0.4
# clip global norm of all gradients by 5
def cifar_config():
return tf.contrib.training.HParams(
stem_multiplier=3.0,
drop_path_keep_prob=0.6,
num_cells=18,
use_aux_head=1,
num_conv_filters=32,
dense_dropout_keep_prob=1.0,
filter_scaling_rate=2.0,
num_reduction_layers=2,
data_format='NHWC',
skip_reduction_layer_input=0,
# 600 epochs with a batch size of 32
# This is used for the drop path probabilities since it needs to increase
# the drop out probability over the course of training.
total_training_steps=937500,
use_bounded_activation=False,
)
# Notes for training large NASNet model on ImageNet
# -------------------------------------
# batch size (per replica): 16
# learning rate: 0.015 * 100
# learning rate decay factor: 0.97
# num epochs per decay: 2.4
# sync sgd with 100 replicas
# auxiliary head loss weighting: 0.4
# label smoothing: 0.1
# clip global norm of all gradients by 10
def large_imagenet_config():
return tf.contrib.training.HParams(
stem_multiplier=3.0,
dense_dropout_keep_prob=0.5,
num_cells=18,
filter_scaling_rate=2.0,
num_conv_filters=168,
drop_path_keep_prob=0.7,
use_aux_head=1,
num_reduction_layers=2,
data_format='NHWC',
skip_reduction_layer_input=1,
total_training_steps=250000,
use_bounded_activation=False,
)
# Notes for training the mobile NASNet ImageNet model
# -------------------------------------
# batch size (per replica): 32
# learning rate: 0.04 * 50
# learning rate scaling factor: 0.97
# num epochs per decay: 2.4
# sync sgd with 50 replicas
# auxiliary head weighting: 0.4
# label smoothing: 0.1
# clip global norm of all gradients by 10
def mobile_imagenet_config():
return tf.contrib.training.HParams(
stem_multiplier=1.0,
dense_dropout_keep_prob=0.5,
num_cells=12,
filter_scaling_rate=2.0,
drop_path_keep_prob=1.0,
num_conv_filters=44,
use_aux_head=1,
num_reduction_layers=2,
data_format='NHWC',
skip_reduction_layer_input=0,
total_training_steps=250000,
use_bounded_activation=False,
)
def _update_hparams(hparams, is_training):
"""Update hparams for given is_training option."""
if not is_training:
hparams.set_hparam('drop_path_keep_prob', 1.0)
def nasnet_cifar_arg_scope(weight_decay=5e-4,
batch_norm_decay=0.9,
batch_norm_epsilon=1e-5):
"""Defines the default arg scope for the NASNet-A Cifar model.
Args:
weight_decay: The weight decay to use for regularizing the model.
batch_norm_decay: Decay for batch norm moving average.
batch_norm_epsilon: Small float added to variance to avoid dividing by zero
in batch norm.
Returns:
An `arg_scope` to use for the NASNet Cifar Model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': batch_norm_decay,
# epsilon to prevent 0s in variance.
'epsilon': batch_norm_epsilon,
'scale': True,
'fused': True,
}
weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
weights_initializer = tf.contrib.layers.variance_scaling_initializer(
mode='FAN_OUT')
with arg_scope([slim.fully_connected, slim.conv2d, slim.separable_conv2d],
weights_regularizer=weights_regularizer,
weights_initializer=weights_initializer):
with arg_scope([slim.fully_connected],
activation_fn=None, scope='FC'):
with arg_scope([slim.conv2d, slim.separable_conv2d],
activation_fn=None, biases_initializer=None):
with arg_scope([slim.batch_norm], **batch_norm_params) as sc:
return sc
def nasnet_mobile_arg_scope(weight_decay=4e-5,
batch_norm_decay=0.9997,
batch_norm_epsilon=1e-3):
"""Defines the default arg scope for the NASNet-A Mobile ImageNet model.
Args:
weight_decay: The weight decay to use for regularizing the model.
batch_norm_decay: Decay for batch norm moving average.
batch_norm_epsilon: Small float added to variance to avoid dividing by zero
in batch norm.
Returns:
An `arg_scope` to use for the NASNet Mobile Model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': batch_norm_decay,
# epsilon to prevent 0s in variance.
'epsilon': batch_norm_epsilon,
'scale': True,
'fused': True,
}
weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
weights_initializer = tf.contrib.layers.variance_scaling_initializer(
mode='FAN_OUT')
with arg_scope([slim.fully_connected, slim.conv2d, slim.separable_conv2d],
weights_regularizer=weights_regularizer,
weights_initializer=weights_initializer):
with arg_scope([slim.fully_connected],
activation_fn=None, scope='FC'):
with arg_scope([slim.conv2d, slim.separable_conv2d],
activation_fn=None, biases_initializer=None):
with arg_scope([slim.batch_norm], **batch_norm_params) as sc:
return sc
def nasnet_large_arg_scope(weight_decay=5e-5,
batch_norm_decay=0.9997,
batch_norm_epsilon=1e-3):
"""Defines the default arg scope for the NASNet-A Large ImageNet model.
Args:
weight_decay: The weight decay to use for regularizing the model.
batch_norm_decay: Decay for batch norm moving average.
batch_norm_epsilon: Small float added to variance to avoid dividing by zero
in batch norm.
Returns:
An `arg_scope` to use for the NASNet Large Model.
"""
batch_norm_params = {
# Decay for the moving averages.
'decay': batch_norm_decay,
# epsilon to prevent 0s in variance.
'epsilon': batch_norm_epsilon,
'scale': True,
'fused': True,
}
weights_regularizer = tf.contrib.layers.l2_regularizer(weight_decay)
weights_initializer = tf.contrib.layers.variance_scaling_initializer(
mode='FAN_OUT')
with arg_scope([slim.fully_connected, slim.conv2d, slim.separable_conv2d],
weights_regularizer=weights_regularizer,
weights_initializer=weights_initializer):
with arg_scope([slim.fully_connected],
activation_fn=None, scope='FC'):
with arg_scope([slim.conv2d, slim.separable_conv2d],
activation_fn=None, biases_initializer=None):
with arg_scope([slim.batch_norm], **batch_norm_params) as sc:
return sc
def _build_aux_head(net, end_points, num_classes, hparams, scope):
"""Auxiliary head used for all models across all datasets."""
activation_fn = tf.nn.relu6 if hparams.use_bounded_activation else tf.nn.relu
with tf.variable_scope(scope):
aux_logits = tf.identity(net)
with tf.variable_scope('aux_logits'):
aux_logits = slim.avg_pool2d(
aux_logits, [5, 5], stride=3, padding='VALID')
aux_logits = slim.conv2d(aux_logits, 128, [1, 1], scope='proj')
aux_logits = slim.batch_norm(aux_logits, scope='aux_bn0')
aux_logits = activation_fn(aux_logits)
# Shape of feature map before the final layer.
shape = aux_logits.shape
if hparams.data_format == 'NHWC':
shape = shape[1:3]
else:
shape = shape[2:4]
aux_logits = slim.conv2d(aux_logits, 768, shape, padding='VALID')
aux_logits = slim.batch_norm(aux_logits, scope='aux_bn1')
aux_logits = activation_fn(aux_logits)
aux_logits = tf.contrib.layers.flatten(aux_logits)
aux_logits = slim.fully_connected(aux_logits, num_classes)
end_points['AuxLogits'] = aux_logits
def _imagenet_stem(inputs, hparams, stem_cell, current_step=None):
"""Stem used for models trained on ImageNet."""
num_stem_cells = 2
# 149 x 149 x 32
num_stem_filters = int(32 * hparams.stem_multiplier)
net = slim.conv2d(
inputs, num_stem_filters, [3, 3], stride=2, scope='conv0',
padding='VALID')
net = slim.batch_norm(net, scope='conv0_bn')
# Run the reduction cells
cell_outputs = [None, net]
filter_scaling = 1.0 / (hparams.filter_scaling_rate**num_stem_cells)
for cell_num in range(num_stem_cells):
net = stem_cell(
net,
scope='cell_stem_{}'.format(cell_num),
filter_scaling=filter_scaling,
stride=2,
prev_layer=cell_outputs[-2],
cell_num=cell_num,
current_step=current_step)
cell_outputs.append(net)
filter_scaling *= hparams.filter_scaling_rate
return net, cell_outputs
def _cifar_stem(inputs, hparams):
"""Stem used for models trained on Cifar."""
num_stem_filters = int(hparams.num_conv_filters * hparams.stem_multiplier)
net = slim.conv2d(
inputs,
num_stem_filters,
3,
scope='l1_stem_3x3')
net = slim.batch_norm(net, scope='l1_stem_bn')
return net, [None, net]
def build_nasnet_cifar(images, num_classes,
is_training=True,
config=None,
current_step=None):
"""Build NASNet model for the Cifar Dataset."""
hparams = cifar_config() if config is None else copy.deepcopy(config)
_update_hparams(hparams, is_training)
if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':
tf.logging.info('A GPU is available on the machine, consider using NCHW '
'data format for increased speed on GPU.')
if hparams.data_format == 'NCHW':
images = tf.transpose(images, [0, 3, 1, 2])
# Calculate the total number of cells in the network
# Add 2 for the reduction cells
total_num_cells = hparams.num_cells + 2
normal_cell = nasnet_utils.NasNetANormalCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
reduction_cell = nasnet_utils.NasNetAReductionCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
with arg_scope([slim.dropout, nasnet_utils.drop_path, slim.batch_norm],
is_training=is_training):
with arg_scope([slim.avg_pool2d,
slim.max_pool2d,
slim.conv2d,
slim.batch_norm,
slim.separable_conv2d,
nasnet_utils.factorized_reduction,
nasnet_utils.global_avg_pool,
nasnet_utils.get_channel_index,
nasnet_utils.get_channel_dim],
data_format=hparams.data_format):
return _build_nasnet_base(images,
normal_cell=normal_cell,
reduction_cell=reduction_cell,
num_classes=num_classes,
hparams=hparams,
is_training=is_training,
stem_type='cifar',
current_step=current_step)
build_nasnet_cifar.default_image_size = 32
def build_nasnet_mobile(images, num_classes,
is_training=True,
final_endpoint=None,
config=None,
current_step=None):
"""Build NASNet Mobile model for the ImageNet Dataset."""
hparams = (mobile_imagenet_config() if config is None
else copy.deepcopy(config))
_update_hparams(hparams, is_training)
if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':
tf.logging.info('A GPU is available on the machine, consider using NCHW '
'data format for increased speed on GPU.')
if hparams.data_format == 'NCHW':
images = tf.transpose(images, [0, 3, 1, 2])
# Calculate the total number of cells in the network
# Add 2 for the reduction cells
total_num_cells = hparams.num_cells + 2
# If ImageNet, then add an additional two for the stem cells
total_num_cells += 2
normal_cell = nasnet_utils.NasNetANormalCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
reduction_cell = nasnet_utils.NasNetAReductionCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
with arg_scope([slim.dropout, nasnet_utils.drop_path, slim.batch_norm],
is_training=is_training):
with arg_scope([slim.avg_pool2d,
slim.max_pool2d,
slim.conv2d,
slim.batch_norm,
slim.separable_conv2d,
nasnet_utils.factorized_reduction,
nasnet_utils.global_avg_pool,
nasnet_utils.get_channel_index,
nasnet_utils.get_channel_dim],
data_format=hparams.data_format):
return _build_nasnet_base(images,
normal_cell=normal_cell,
reduction_cell=reduction_cell,
num_classes=num_classes,
hparams=hparams,
is_training=is_training,
stem_type='imagenet',
final_endpoint=final_endpoint,
current_step=current_step)
build_nasnet_mobile.default_image_size = 224
def build_nasnet_large(images, num_classes,
is_training=True,
final_endpoint=None,
config=None,
current_step=None):
"""Build NASNet Large model for the ImageNet Dataset."""
hparams = (large_imagenet_config() if config is None
else copy.deepcopy(config))
_update_hparams(hparams, is_training)
if tf.test.is_gpu_available() and hparams.data_format == 'NHWC':
tf.logging.info('A GPU is available on the machine, consider using NCHW '
'data format for increased speed on GPU.')
if hparams.data_format == 'NCHW':
images = tf.transpose(images, [0, 3, 1, 2])
# Calculate the total number of cells in the network
# Add 2 for the reduction cells
total_num_cells = hparams.num_cells + 2
# If ImageNet, then add an additional two for the stem cells
total_num_cells += 2
normal_cell = nasnet_utils.NasNetANormalCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
reduction_cell = nasnet_utils.NasNetAReductionCell(
hparams.num_conv_filters, hparams.drop_path_keep_prob,
total_num_cells, hparams.total_training_steps,
hparams.use_bounded_activation)
with arg_scope([slim.dropout, nasnet_utils.drop_path, slim.batch_norm],
is_training=is_training):
with arg_scope([slim.avg_pool2d,
slim.max_pool2d,
slim.conv2d,
slim.batch_norm,
slim.separable_conv2d,
nasnet_utils.factorized_reduction,
nasnet_utils.global_avg_pool,
nasnet_utils.get_channel_index,
nasnet_utils.get_channel_dim],
data_format=hparams.data_format):
return _build_nasnet_base(images,
normal_cell=normal_cell,
reduction_cell=reduction_cell,
num_classes=num_classes,
hparams=hparams,
is_training=is_training,
stem_type='imagenet',
final_endpoint=final_endpoint,
current_step=current_step)
build_nasnet_large.default_image_size = 331
def _build_nasnet_base(images,
normal_cell,
reduction_cell,
num_classes,
hparams,
is_training,
stem_type,
final_endpoint=None,
current_step=None):
"""Constructs a NASNet image model."""
end_points = {}
def add_and_check_endpoint(endpoint_name, net):
end_points[endpoint_name] = net
return final_endpoint and (endpoint_name == final_endpoint)
# Find where to place the reduction cells or stride normal cells
reduction_indices = nasnet_utils.calc_reduction_layers(
hparams.num_cells, hparams.num_reduction_layers)
stem_cell = reduction_cell
if stem_type == 'imagenet':
stem = lambda: _imagenet_stem(images, hparams, stem_cell)
elif stem_type == 'cifar':
stem = lambda: _cifar_stem(images, hparams)
else:
raise ValueError('Unknown stem_type: ', stem_type)
net, cell_outputs = stem()
if add_and_check_endpoint('Stem', net): return net, end_points
# Setup for building in the auxiliary head.
aux_head_cell_idxes = []
if len(reduction_indices) >= 2:
aux_head_cell_idxes.append(reduction_indices[1] - 1)
# Run the cells
filter_scaling = 1.0
# true_cell_num accounts for the stem cells
true_cell_num = 2 if stem_type == 'imagenet' else 0
activation_fn = tf.nn.relu6 if hparams.use_bounded_activation else tf.nn.relu
for cell_num in range(hparams.num_cells):
stride = 1
if hparams.skip_reduction_layer_input:
prev_layer = cell_outputs[-2]
if cell_num in reduction_indices:
filter_scaling *= hparams.filter_scaling_rate
net = reduction_cell(
net,
scope='reduction_cell_{}'.format(reduction_indices.index(cell_num)),
filter_scaling=filter_scaling,
stride=2,
prev_layer=cell_outputs[-2],
cell_num=true_cell_num,
current_step=current_step)
if add_and_check_endpoint(
'Reduction_Cell_{}'.format(reduction_indices.index(cell_num)), net):
return net, end_points
true_cell_num += 1
cell_outputs.append(net)
if not hparams.skip_reduction_layer_input:
prev_layer = cell_outputs[-2]
net = normal_cell(
net,
scope='cell_{}'.format(cell_num),
filter_scaling=filter_scaling,
stride=stride,
prev_layer=prev_layer,
cell_num=true_cell_num,
current_step=current_step)
if add_and_check_endpoint('Cell_{}'.format(cell_num), net):
return net, end_points
true_cell_num += 1
if (hparams.use_aux_head and cell_num in aux_head_cell_idxes and
num_classes and is_training):
aux_net = activation_fn(net)
_build_aux_head(aux_net, end_points, num_classes, hparams,
scope='aux_{}'.format(cell_num))
cell_outputs.append(net)
# Final softmax layer
with tf.variable_scope('final_layer'):
net = activation_fn(net)
net = nasnet_utils.global_avg_pool(net)
if add_and_check_endpoint('global_pool', net) or not num_classes:
return net, end_points
net = slim.dropout(net, hparams.dense_dropout_keep_prob, scope='dropout')
logits = slim.fully_connected(net, num_classes)
if add_and_check_endpoint('Logits', logits):
return net, end_points
predictions = tf.nn.softmax(logits, name='predictions')
if add_and_check_endpoint('Predictions', predictions):
return net, end_points
return logits, end_points
|
TensorFlow/Recommendation/VAE-CF/vae/models | models | vae | # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import tensorflow as tf
from vae.models.layers import DenseFromSparse
TRAINING = 0
VALIDATION = 1
QUERY = 2
class _VAEGraph(tf.keras.Model):
def __init__(self, encoder_dims, decoder_dims, activation='tanh'):
super(_VAEGraph, self).__init__()
if encoder_dims[-1] != decoder_dims[0]:
raise Exception("encoder/decoder dims mismatch")
self.input_dim = encoder_dims[0]
self.output_dim = decoder_dims[-1]
self.activation = tf.nn.tanh if activation == 'tanh' else tf.nn.relu
self.encoder = self.encoder_model(encoder_dims[1:])
self.decoder = self.decoder_model(decoder_dims[1:])
def call(self, inputs: tf.SparseTensor, mode):
""" Get handlers to VAE output
:param inputs: batch_size * items_count as sparse tensor.
:param mode: Either 0,1 or 2 representing type of network
:return: Tuple of 3 tensors:
1. decoder output: batch_size * items_count tensor
2. latent_mean: mean tensor between encoder and decoder. It has size batch_size * size_of_mean_vector
3. latent_log_var: tesor containing logarithms of variances. It has size batch_size * size_of_var_vector
"""
latent_all = self.encoder(inputs, training=(mode is TRAINING))
latent_mean = latent_all[:, 0]
latent_log_var = latent_all[:, 1]
latent_std = tf.exp(0.5 * latent_log_var)
# reparametrization trick
batch = tf.shape(latent_mean)[0]
dim = tf.shape(latent_mean)[1]
epsilon = tf.random_normal(shape=(batch, dim))
decoder_input = latent_mean + (int(mode is TRAINING)) * latent_std * epsilon
decoder_output = self.decoder(decoder_input, training=(mode is TRAINING))
return decoder_output, latent_mean, latent_log_var
def encoder_model(self, dims):
assert dims
last = dims[-1]
dims[-1] = 2 * last
layers = tf.keras.layers
return tf.keras.Sequential(
[DenseFromSparse(
dims[0],
activation=self.activation,
name="encoder_{}".format(dims[0]),
kernel_initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.truncated_normal_initializer(stddev=0.001),
kernel_regularizer=tf.contrib.layers.l2_regularizer)
] + [
layers.Dense(
d,
activation=self.activation,
name="encoder_{}".format(d),
kernel_initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.truncated_normal_initializer(stddev=0.001),
kernel_regularizer=tf.contrib.layers.l2_regularizer)
for d in dims[1:-1]
] + [
layers.Dense(
dims[-1],
name="encoder_{}".format(dims[-1]),
kernel_initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.truncated_normal_initializer(stddev=0.001),
kernel_regularizer=tf.contrib.layers.l2_regularizer)
] + [layers.Reshape(target_shape=(2, last))])
def decoder_model(self, dims):
assert dims
layers = tf.keras.layers
return tf.keras.Sequential([
layers.Dense(
d,
activation=self.activation,
name="decoder_{}".format(d),
kernel_initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.truncated_normal_initializer(stddev=0.001),
kernel_regularizer=tf.contrib.layers.l2_regularizer) for d in dims[:-1]
] + [
layers.Dense(
dims[-1],
name="decoder_{}".format(dims[-1]),
kernel_initializer=tf.contrib.layers.xavier_initializer(),
bias_initializer=tf.truncated_normal_initializer(stddev=0.001),
kernel_regularizer=tf.contrib.layers.l2_regularizer)
])
|
Tools/PyTorch/TimeSeriesPredictionPlatform/inference | inference | launch_inference_server | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import shutil
import subprocess
from typing import Dict, List, Optional, Tuple
import dllogger
import shutil
import hydra
from triton.dataloader import get_dataloader_fn
from loggers.log_helper import setup_logger
def run_server_launch(config):
cfg = config
# export model
output_path = os.path.join(cfg.checkpoint, "deployment")
tspp_main_dir = os.path.sep + os.path.join(*(os.getcwd().split(os.path.sep)[:-3]))
# get the actual model name
if not os.path.isdir(os.path.join(output_path, "navigator_workspace")) or not os.path.isdir(
os.path.join(output_path, "navigator_workspace/model-store")
):
if os.path.isdir(os.path.join(output_path, "navigator_workspace/final-model-store")):
shutil.copytree(os.path.join(output_path, "navigator_workspace/final-model-store"), os.path.join(output_path, "navigator_workspace/model-store"))
else:
assert (
False
), "This checkpoint directory is not configured correctly, there should be a dir/deployment/navigator_workspace/model-store/ directory"
files_in_store = list(os.listdir(os.path.join(output_path, "navigator_workspace/model-store")))
if len(files_in_store) < 1:
assert False, "There needs to be exactly 1 model in the model-store directory"
model_name = cfg.get("model_name") if cfg.get("model_name", None) else files_in_store[0]
# deploy
subprocess.run(["bash", "inference/deploy.sh", output_path, str(cfg.gpu)], cwd=tspp_main_dir, check=True)
|
Tools/PyTorch/TimeSeriesPredictionPlatform/conf/trainer | trainer | stattrainer | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_target_: training.trainer.StatTrainer
config:
device: cpu
|
TensorFlow2/LanguageModeling/BERT/data | data | BooksDownloader | # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import subprocess
class BooksDownloader:
def __init__(self, save_path):
self.save_path = save_path
pass
def download(self):
bookscorpus_download_command = 'python3 /workspace/bookcorpus/download_files.py --list /workspace/bookcorpus/url_list.jsonl --out'
bookscorpus_download_command += ' ' + self.save_path + '/bookscorpus'
bookscorpus_download_command += ' --trash-bad-count'
bookscorpus_download_process = subprocess.run(bookscorpus_download_command, shell=True, check=True) |
TensorFlow2/LanguageModeling/BERT/scripts/configs | configs | squad_config | #!/usr/bin/env bash
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
# Full SQuAD training configs for NVIDIA DGX A100 (8x NVIDIA A100 40GB GPU)
dgxa100_8gpu_fp16 ()
{
batch_size=76
learning_rate=3e-5
precision=fp16
use_xla=true
num_gpu=8
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
dgxa100_8gpu_tf32 ()
{
batch_size=38
learning_rate=7.5e-6
precision=tf32
use_xla=true
num_gpu=8
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
# Full SQuAD training configs for NVIDIA DGX-2H (16x NVIDIA V100 32GB GPU)
dgx2_16gpu_fp16 ()
{
batch_size=12
learning_rate=3.75e-6
precision=fp16
use_xla=true
num_gpu=16
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
dgx2_16gpu_fp32 ()
{
batch_size=8
learning_rate=2.5e-6
precision=fp32
use_xla=true
num_gpu=16
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
# Full SQuAD training configs for NVIDIA DGX-1 (8x NVIDIA V100 16GB GPU)
dgx1_8gpu_fp16 ()
{
batch_size=6
learning_rate=5e-6
precision=fp16
use_xla=true
num_gpu=8
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
dgx1_8gpu_fp32 ()
{
batch_size=3
learning_rate=5e-6
precision=fp32
use_xla=true
num_gpu=8
bert_model="large"
echo $num_gpu $batch_size $learning_rate $precision $use_xla $bert_model
}
|
Tools/PyTorch/TimeSeriesPredictionPlatform/models/tft_pyt/triton/deployment_toolkit/model_analyzer | model_analyzer | model_analyzer | # Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import subprocess
from subprocess import CalledProcessError
from .exceptions import ModelAnalyzerException
SERVER_OUTPUT_TIMEOUT_SECS = 5
LOGGER = logging.getLogger(__name__)
class ModelAnalyzerMode:
PROFILE = "profile"
ANALYZE = "analyze"
REPORT = "report"
class ModelAnalyzerReportMode:
OFFLINE = "offline"
ONLINE = "online"
class ModelAnalyzer:
"""
Concrete Implementation of Model Analyzer interface that runs
analyzer locally as as subprocess.
"""
_analyzer_path = "model-analyzer"
def __init__(self, config):
"""
Parameters
----------
config : AnalyzerConfig
the config object containing arguments for this server instance
"""
self._analyzer_process = None
self._analyzer_config = config
self._log = None
def run(self, mode: str, verbose: bool = False, quiet: bool = False, report_mode: str = None):
"""
Starts the model analyzer locally
"""
if self._analyzer_path:
cmd = [self._analyzer_path]
if verbose:
cmd += ["--verbose"]
if quiet:
cmd += ["--quiet"]
if report_mode:
cmd += ["-m"]
cmd += [report_mode]
cmd += [mode]
cmd += self._analyzer_config.to_cli_string().split()
LOGGER.debug(f"Model Analyze command: {cmd}")
try:
subprocess.run(cmd, check=True, start_new_session=True)
except CalledProcessError as e:
raise ModelAnalyzerException(
f"Running {self._analyzer_path} with {e.cmd} failed with"
f" exit status {e.returncode} : {e.output}"
)
|
PyTorch/SpeechSynthesis/FastPitch/fastpitch | fastpitch | arg_parser | # *****************************************************************************
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the NVIDIA CORPORATION nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
# *****************************************************************************
import argparse
def parse_fastpitch_args(parent, add_help=False):
"""
Parse commandline arguments.
"""
parser = argparse.ArgumentParser(parents=[parent], add_help=add_help,
allow_abbrev=False)
io = parser.add_argument_group('io parameters')
io.add_argument('--n-mel-channels', default=80, type=int,
help='Number of bins in mel-spectrograms')
io.add_argument('--max-seq-len', default=2048, type=int,
help='')
symbols = parser.add_argument_group('symbols parameters')
symbols.add_argument('--n-symbols', default=148, type=int,
help='Number of symbols in dictionary')
symbols.add_argument('--padding-idx', default=0, type=int,
help='Index of padding symbol in dictionary')
symbols.add_argument('--symbols-embedding-dim', default=384, type=int,
help='Input embedding dimension')
in_fft = parser.add_argument_group('input FFT parameters')
in_fft.add_argument('--in-fft-n-layers', default=6, type=int,
help='Number of FFT blocks')
in_fft.add_argument('--in-fft-n-heads', default=1, type=int,
help='Number of attention heads')
in_fft.add_argument('--in-fft-d-head', default=64, type=int,
help='Dim of attention heads')
in_fft.add_argument('--in-fft-conv1d-kernel-size', default=3, type=int,
help='Conv-1D kernel size')
in_fft.add_argument('--in-fft-conv1d-filter-size', default=1536, type=int,
help='Conv-1D filter size')
in_fft.add_argument('--in-fft-output-size', default=384, type=int,
help='Output dim')
in_fft.add_argument('--p-in-fft-dropout', default=0.1, type=float,
help='Dropout probability')
in_fft.add_argument('--p-in-fft-dropatt', default=0.1, type=float,
help='Multi-head attention dropout')
in_fft.add_argument('--p-in-fft-dropemb', default=0.0, type=float,
help='Dropout added to word+positional embeddings')
out_fft = parser.add_argument_group('output FFT parameters')
out_fft.add_argument('--out-fft-n-layers', default=6, type=int,
help='Number of FFT blocks')
out_fft.add_argument('--out-fft-n-heads', default=1, type=int,
help='Number of attention heads')
out_fft.add_argument('--out-fft-d-head', default=64, type=int,
help='Dim of attention head')
out_fft.add_argument('--out-fft-conv1d-kernel-size', default=3, type=int,
help='Conv-1D kernel size')
out_fft.add_argument('--out-fft-conv1d-filter-size', default=1536, type=int,
help='Conv-1D filter size')
out_fft.add_argument('--out-fft-output-size', default=384, type=int,
help='Output dim')
out_fft.add_argument('--p-out-fft-dropout', default=0.1, type=float,
help='Dropout probability for out_fft')
out_fft.add_argument('--p-out-fft-dropatt', default=0.1, type=float,
help='Multi-head attention dropout')
out_fft.add_argument('--p-out-fft-dropemb', default=0.0, type=float,
help='Dropout added to word+positional embeddings')
dur_pred = parser.add_argument_group('duration predictor parameters')
dur_pred.add_argument('--dur-predictor-kernel-size', default=3, type=int,
help='Duration predictor conv-1D kernel size')
dur_pred.add_argument('--dur-predictor-filter-size', default=256, type=int,
help='Duration predictor conv-1D filter size')
dur_pred.add_argument('--p-dur-predictor-dropout', default=0.1, type=float,
help='Dropout probability for duration predictor')
dur_pred.add_argument('--dur-predictor-n-layers', default=2, type=int,
help='Number of conv-1D layers')
pitch_pred = parser.add_argument_group('pitch predictor parameters')
pitch_pred.add_argument('--pitch-predictor-kernel-size', default=3, type=int,
help='Pitch predictor conv-1D kernel size')
pitch_pred.add_argument('--pitch-predictor-filter-size', default=256, type=int,
help='Pitch predictor conv-1D filter size')
pitch_pred.add_argument('--p-pitch-predictor-dropout', default=0.1, type=float,
help='Pitch probability for pitch predictor')
pitch_pred.add_argument('--pitch-predictor-n-layers', default=2, type=int,
help='Number of conv-1D layers')
energy_pred = parser.add_argument_group('energy predictor parameters')
energy_pred.add_argument('--energy-conditioning', action='store_true')
energy_pred.add_argument('--energy-predictor-kernel-size', default=3, type=int,
help='Pitch predictor conv-1D kernel size')
energy_pred.add_argument('--energy-predictor-filter-size', default=256, type=int,
help='Pitch predictor conv-1D filter size')
energy_pred.add_argument('--p-energy-predictor-dropout', default=0.1, type=float,
help='Pitch probability for energy predictor')
energy_pred.add_argument('--energy-predictor-n-layers', default=2, type=int,
help='Number of conv-1D layers')
cond = parser.add_argument_group('conditioning parameters')
cond.add_argument('--pitch-embedding-kernel-size', default=3, type=int,
help='Pitch embedding conv-1D kernel size')
cond.add_argument('--energy-embedding-kernel-size', default=3, type=int,
help='Pitch embedding conv-1D kernel size')
cond.add_argument('--speaker-emb-weight', type=float, default=1.0,
help='Scale speaker embedding')
return parser
|
PyTorch/SpeechRecognition/QuartzNet/quartznet | quartznet | config | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import copy
import inspect
from ast import literal_eval
from contextlib import suppress
from numbers import Number
import yaml
from common.audio import GainPerturbation, ShiftPerturbation, SpeedPerturbation
from common.dataset import AudioDataset
from common.features import (CutoutAugment, FilterbankFeatures, SpecAugment)
from quartznet.model import JasperDecoderForCTC, JasperBlock, JasperEncoder
def default_args(klass):
sig = inspect.signature(klass.__init__)
return {k: v.default for k, v in sig.parameters.items() if k != 'self'}
def load(fpath):
cfg = yaml.safe_load(open(fpath, 'r'))
# Reload to deep copy shallow copies, which were made with yaml anchors
yaml.Dumper.ignore_aliases = lambda *args: True
cfg = yaml.dump(cfg)
cfg = yaml.safe_load(cfg)
return cfg
def validate_and_fill(klass, user_conf, ignore_unk=[], optional=[]):
conf = default_args(klass)
for k, v in user_conf.items():
assert k in conf or k in ignore_unk, f'Unknown param {k} for {klass}'
conf[k] = v
# Keep only mandatory or optional-nonempty
conf = {k: v for k, v in conf.items()
if k not in optional or v is not inspect.Parameter.empty}
# Validate
for k, v in conf.items():
assert v is not inspect.Parameter.empty, \
f'Value for {k} not specified for {klass}'
return conf
def input(conf_yaml, split='train'):
conf = copy.deepcopy(conf_yaml[f'input_{split}'])
conf_dataset = conf.pop('audio_dataset')
conf_features = conf.pop('filterbank_features')
# Validate known inner classes
inner_classes = [
(conf_dataset, 'speed_perturbation', SpeedPerturbation),
(conf_dataset, 'gain_perturbation', GainPerturbation),
(conf_dataset, 'shift_perturbation', ShiftPerturbation),
(conf_features, 'spec_augment', SpecAugment),
(conf_features, 'cutout_augment', CutoutAugment),
]
for conf_tgt, key, klass in inner_classes:
if key in conf_tgt:
conf_tgt[key] = validate_and_fill(klass, conf_tgt[key])
for k in conf:
raise ValueError(f'Unknown key {k}')
# Validate outer classes
conf_dataset = validate_and_fill(
AudioDataset, conf_dataset,
optional=['data_dir', 'labels', 'manifest_fpaths'])
# klass = feature_class(conf_features['feature_type'])
# conf_features = validate_and_fill(
# klass, conf_features, ignore_unk=['feature_type'])
conf_features = validate_and_fill(
FilterbankFeatures, conf_features) # , ignore_unk=['feature_type'])
# Check params shared between classes
shared = ['sample_rate', 'max_duration', 'pad_to_max_duration']
for sh in shared:
assert conf_dataset[sh] == conf_features[sh], (
f'{sh} should match in Dataset and FeatureProcessor: '
f'{conf_dataset[sh]}, {conf_features[sh]}')
return conf_dataset, conf_features
def encoder(conf):
"""Validate config for JasperEncoder and subsequent JasperBlocks"""
# Validate, but don't overwrite with defaults
for blk in conf['quartznet']['encoder']['blocks']:
validate_and_fill(JasperBlock, blk, optional=['infilters'],
ignore_unk=['residual_dense'])
return validate_and_fill(JasperEncoder, conf['quartznet']['encoder'])
def decoder(conf, n_classes):
decoder_kw = {'n_classes': n_classes, **conf['quartznet']['decoder']}
return validate_and_fill(JasperDecoderForCTC, decoder_kw)
def apply_config_overrides(conf, args):
if args.override_config is None:
return
for override_key_val in args.override_config:
key, val = override_key_val.split('=')
with suppress(TypeError, ValueError):
val = literal_eval(val)
apply_nested_config_override(conf, key, val)
def apply_nested_config_override(conf, key_str, val):
fields = key_str.split('.')
for f in fields[:-1]:
conf = conf[f]
f = fields[-1]
assert (f not in conf
or type(val) is type(conf[f])
or (isinstance(val, Number) and isinstance(conf[f], Number)))
conf[f] = val
|
Tools/PyTorch/TimeSeriesPredictionPlatform/conf/trainer | trainer | xgbtrainer | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
_target_: training.trainer.XGBTrainer
defaults:
- callbacks: standard
config:
device: cuda
|
TensorFlow/Recommendation/NCF | NCF | LICENSE | Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018 NVIDIA Corporation
Copyright 2018 The MLPerf Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. |
TensorFlow2/Segmentation/Contrib/UNet3P/models | models | backbones | """
Unet3+ backbones
"""
import tensorflow as tf
import tensorflow.keras as k
from .unet3plus_utils import conv_block
def vgg16_backbone(input_layer, ):
""" VGG-16 backbone as encoder for UNet3P """
base_model = tf.keras.applications.VGG16(
input_tensor=input_layer,
weights=None,
include_top=False
)
# block 1
e1 = base_model.get_layer("block1_conv2").output # 320, 320, 64
# block 2
e2 = base_model.get_layer("block2_conv2").output # 160, 160, 128
# block 3
e3 = base_model.get_layer("block3_conv3").output # 80, 80, 256
# block 4
e4 = base_model.get_layer("block4_conv3").output # 40, 40, 512
# block 5
e5 = base_model.get_layer("block5_conv3").output # 20, 20, 512
return [e1, e2, e3, e4, e5]
def vgg19_backbone(input_layer, ):
""" VGG-19 backbone as encoder for UNet3P """
base_model = tf.keras.applications.VGG19(
input_tensor=input_layer,
weights=None,
include_top=False
)
# block 1
e1 = base_model.get_layer("block1_conv2").output # 320, 320, 64
# block 2
e2 = base_model.get_layer("block2_conv2").output # 160, 160, 128
# block 3
e3 = base_model.get_layer("block3_conv4").output # 80, 80, 256
# block 4
e4 = base_model.get_layer("block4_conv4").output # 40, 40, 512
# block 5
e5 = base_model.get_layer("block5_conv4").output # 20, 20, 512
return [e1, e2, e3, e4, e5]
def unet3plus_backbone(input_layer, filters):
""" UNet3+ own backbone """
""" Encoder"""
# block 1
e1 = conv_block(input_layer, filters[0]) # 320*320*64
# block 2
e2 = k.layers.MaxPool2D(pool_size=(2, 2))(e1) # 160*160*64
e2 = conv_block(e2, filters[1]) # 160*160*128
# block 3
e3 = k.layers.MaxPool2D(pool_size=(2, 2))(e2) # 80*80*128
e3 = conv_block(e3, filters[2]) # 80*80*256
# block 4
e4 = k.layers.MaxPool2D(pool_size=(2, 2))(e3) # 40*40*256
e4 = conv_block(e4, filters[3]) # 40*40*512
# block 5, bottleneck layer
e5 = k.layers.MaxPool2D(pool_size=(2, 2))(e4) # 20*20*512
e5 = conv_block(e5, filters[4]) # 20*20*1024
return [e1, e2, e3, e4, e5]
|
TensorFlow/Detection/SSD/models/research/slim/deployment | deployment | model_deploy | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Deploy Slim models across multiple clones and replicas.
# TODO(sguada) docstring paragraph by (a) motivating the need for the file and
# (b) defining clones.
# TODO(sguada) describe the high-level components of model deployment.
# E.g. "each model deployment is composed of several parts: a DeploymentConfig,
# which captures A, B and C, an input_fn which loads data.. etc
To easily train a model on multiple GPUs or across multiple machines this
module provides a set of helper functions: `create_clones`,
`optimize_clones` and `deploy`.
Usage:
g = tf.Graph()
# Set up DeploymentConfig
config = model_deploy.DeploymentConfig(num_clones=2, clone_on_cpu=True)
# Create the global step on the device storing the variables.
with tf.device(config.variables_device()):
global_step = slim.create_global_step()
# Define the inputs
with tf.device(config.inputs_device()):
images, labels = LoadData(...)
inputs_queue = slim.data.prefetch_queue((images, labels))
# Define the optimizer.
with tf.device(config.optimizer_device()):
optimizer = tf.train.MomentumOptimizer(FLAGS.learning_rate, FLAGS.momentum)
# Define the model including the loss.
def model_fn(inputs_queue):
images, labels = inputs_queue.dequeue()
predictions = CreateNetwork(images)
slim.losses.log_loss(predictions, labels)
model_dp = model_deploy.deploy(config, model_fn, [inputs_queue],
optimizer=optimizer)
# Run training.
slim.learning.train(model_dp.train_op, my_log_dir,
summary_op=model_dp.summary_op)
The Clone namedtuple holds together the values associated with each call to
model_fn:
* outputs: The return values of the calls to `model_fn()`.
* scope: The scope used to create the clone.
* device: The device used to create the clone.
DeployedModel namedtuple, holds together the values needed to train multiple
clones:
* train_op: An operation that run the optimizer training op and include
all the update ops created by `model_fn`. Present only if an optimizer
was specified.
* summary_op: An operation that run the summaries created by `model_fn`
and process_gradients.
* total_loss: A `Tensor` that contains the sum of all losses created by
`model_fn` plus the regularization losses.
* clones: List of `Clone` tuples returned by `create_clones()`.
DeploymentConfig parameters:
* num_clones: Number of model clones to deploy in each replica.
* clone_on_cpu: True if clones should be placed on CPU.
* replica_id: Integer. Index of the replica for which the model is
deployed. Usually 0 for the chief replica.
* num_replicas: Number of replicas to use.
* num_ps_tasks: Number of tasks for the `ps` job. 0 to not use replicas.
* worker_job_name: A name for the worker job.
* ps_job_name: A name for the parameter server job.
TODO(sguada):
- describe side effect to the graph.
- what happens to summaries and update_ops.
- which graph collections are altered.
- write a tutorial on how to use this.
- analyze the possibility of calling deploy more than once.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import tensorflow as tf
slim = tf.contrib.slim
__all__ = ['create_clones',
'deploy',
'optimize_clones',
'DeployedModel',
'DeploymentConfig',
'Clone',
]
# Namedtuple used to represent a clone during deployment.
Clone = collections.namedtuple('Clone',
['outputs', # Whatever model_fn() returned.
'scope', # The scope used to create it.
'device', # The device used to create.
])
# Namedtuple used to represent a DeployedModel, returned by deploy().
DeployedModel = collections.namedtuple('DeployedModel',
['train_op', # The `train_op`
'summary_op', # The `summary_op`
'total_loss', # The loss `Tensor`
'clones', # A list of `Clones` tuples.
])
# Default parameters for DeploymentConfig
_deployment_params = {'num_clones': 1,
'clone_on_cpu': False,
'replica_id': 0,
'num_replicas': 1,
'num_ps_tasks': 0,
'worker_job_name': 'worker',
'ps_job_name': 'ps'}
def create_clones(config, model_fn, args=None, kwargs=None):
"""Creates multiple clones according to config using a `model_fn`.
The returned values of `model_fn(*args, **kwargs)` are collected along with
the scope and device used to created it in a namedtuple
`Clone(outputs, scope, device)`
Note: it is assumed that any loss created by `model_fn` is collected at
the tf.GraphKeys.LOSSES collection.
To recover the losses, summaries or update_ops created by the clone use:
```python
losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)
summaries = tf.get_collection(tf.GraphKeys.SUMMARIES, clone.scope)
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, clone.scope)
```
The deployment options are specified by the config object and support
deploying one or several clones on different GPUs and one or several replicas
of such clones.
The argument `model_fn` is called `config.num_clones` times to create the
model clones as `model_fn(*args, **kwargs)`.
If `config` specifies deployment on multiple replicas then the default
tensorflow device is set appropriatly for each call to `model_fn` and for the
slim variable creation functions: model and global variables will be created
on the `ps` device, the clone operations will be on the `worker` device.
Args:
config: A DeploymentConfig object.
model_fn: A callable. Called as `model_fn(*args, **kwargs)`
args: Optional list of arguments to pass to `model_fn`.
kwargs: Optional list of keyword arguments to pass to `model_fn`.
Returns:
A list of namedtuples `Clone`.
"""
clones = []
args = args or []
kwargs = kwargs or {}
with slim.arg_scope([slim.model_variable, slim.variable],
device=config.variables_device()):
# Create clones.
for i in range(0, config.num_clones):
with tf.name_scope(config.clone_scope(i)) as clone_scope:
clone_device = config.clone_device(i)
with tf.device(clone_device):
with tf.variable_scope(tf.get_variable_scope(),
reuse=True if i > 0 else None):
outputs = model_fn(*args, **kwargs)
clones.append(Clone(outputs, clone_scope, clone_device))
return clones
def _gather_clone_loss(clone, num_clones, regularization_losses):
"""Gather the loss for a single clone.
Args:
clone: A Clone namedtuple.
num_clones: The number of clones being deployed.
regularization_losses: Possibly empty list of regularization_losses
to add to the clone losses.
Returns:
A tensor for the total loss for the clone. Can be None.
"""
# The return value.
sum_loss = None
# Individual components of the loss that will need summaries.
clone_loss = None
regularization_loss = None
# Compute and aggregate losses on the clone device.
with tf.device(clone.device):
all_losses = []
clone_losses = tf.get_collection(tf.GraphKeys.LOSSES, clone.scope)
if clone_losses:
clone_loss = tf.add_n(clone_losses, name='clone_loss')
if num_clones > 1:
clone_loss = tf.div(clone_loss, 1.0 * num_clones,
name='scaled_clone_loss')
all_losses.append(clone_loss)
if regularization_losses:
regularization_loss = tf.add_n(regularization_losses,
name='regularization_loss')
all_losses.append(regularization_loss)
if all_losses:
sum_loss = tf.add_n(all_losses)
# Add the summaries out of the clone device block.
if clone_loss is not None:
tf.summary.scalar('/'.join(filter(None,
['Losses', clone.scope, 'clone_loss'])),
clone_loss)
if regularization_loss is not None:
tf.summary.scalar('Losses/regularization_loss', regularization_loss)
return sum_loss
def _optimize_clone(optimizer, clone, num_clones, regularization_losses,
**kwargs):
"""Compute losses and gradients for a single clone.
Args:
optimizer: A tf.Optimizer object.
clone: A Clone namedtuple.
num_clones: The number of clones being deployed.
regularization_losses: Possibly empty list of regularization_losses
to add to the clone losses.
**kwargs: Dict of kwarg to pass to compute_gradients().
Returns:
A tuple (clone_loss, clone_grads_and_vars).
- clone_loss: A tensor for the total loss for the clone. Can be None.
- clone_grads_and_vars: List of (gradient, variable) for the clone.
Can be empty.
"""
sum_loss = _gather_clone_loss(clone, num_clones, regularization_losses)
clone_grad = None
if sum_loss is not None:
with tf.device(clone.device):
clone_grad = optimizer.compute_gradients(sum_loss, **kwargs)
return sum_loss, clone_grad
def optimize_clones(clones, optimizer,
regularization_losses=None,
**kwargs):
"""Compute clone losses and gradients for the given list of `Clones`.
Note: The regularization_losses are added to the first clone losses.
Args:
clones: List of `Clones` created by `create_clones()`.
optimizer: An `Optimizer` object.
regularization_losses: Optional list of regularization losses. If None it
will gather them from tf.GraphKeys.REGULARIZATION_LOSSES. Pass `[]` to
exclude them.
**kwargs: Optional list of keyword arguments to pass to `compute_gradients`.
Returns:
A tuple (total_loss, grads_and_vars).
- total_loss: A Tensor containing the average of the clone losses including
the regularization loss.
- grads_and_vars: A List of tuples (gradient, variable) containing the sum
of the gradients for each variable.
"""
grads_and_vars = []
clones_losses = []
num_clones = len(clones)
if regularization_losses is None:
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
for clone in clones:
with tf.name_scope(clone.scope):
clone_loss, clone_grad = _optimize_clone(
optimizer, clone, num_clones, regularization_losses, **kwargs)
if clone_loss is not None:
clones_losses.append(clone_loss)
grads_and_vars.append(clone_grad)
# Only use regularization_losses for the first clone
regularization_losses = None
# Compute the total_loss summing all the clones_losses.
total_loss = tf.add_n(clones_losses, name='total_loss')
# Sum the gradients across clones.
grads_and_vars = _sum_clones_gradients(grads_and_vars)
return total_loss, grads_and_vars
def deploy(config,
model_fn,
args=None,
kwargs=None,
optimizer=None,
summarize_gradients=False):
"""Deploys a Slim-constructed model across multiple clones.
The deployment options are specified by the config object and support
deploying one or several clones on different GPUs and one or several replicas
of such clones.
The argument `model_fn` is called `config.num_clones` times to create the
model clones as `model_fn(*args, **kwargs)`.
The optional argument `optimizer` is an `Optimizer` object. If not `None`,
the deployed model is configured for training with that optimizer.
If `config` specifies deployment on multiple replicas then the default
tensorflow device is set appropriatly for each call to `model_fn` and for the
slim variable creation functions: model and global variables will be created
on the `ps` device, the clone operations will be on the `worker` device.
Args:
config: A `DeploymentConfig` object.
model_fn: A callable. Called as `model_fn(*args, **kwargs)`
args: Optional list of arguments to pass to `model_fn`.
kwargs: Optional list of keyword arguments to pass to `model_fn`.
optimizer: Optional `Optimizer` object. If passed the model is deployed
for training with that optimizer.
summarize_gradients: Whether or not add summaries to the gradients.
Returns:
A `DeployedModel` namedtuple.
"""
# Gather initial summaries.
summaries = set(tf.get_collection(tf.GraphKeys.SUMMARIES))
# Create Clones.
clones = create_clones(config, model_fn, args, kwargs)
first_clone = clones[0]
# Gather update_ops from the first clone. These contain, for example,
# the updates for the batch_norm variables created by model_fn.
update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS, first_clone.scope)
train_op = None
total_loss = None
with tf.device(config.optimizer_device()):
if optimizer:
# Place the global step on the device storing the variables.
with tf.device(config.variables_device()):
global_step = slim.get_or_create_global_step()
# Compute the gradients for the clones.
total_loss, clones_gradients = optimize_clones(clones, optimizer)
if clones_gradients:
if summarize_gradients:
# Add summaries to the gradients.
summaries |= set(_add_gradients_summaries(clones_gradients))
# Create gradient updates.
grad_updates = optimizer.apply_gradients(clones_gradients,
global_step=global_step)
update_ops.append(grad_updates)
update_op = tf.group(*update_ops)
with tf.control_dependencies([update_op]):
train_op = tf.identity(total_loss, name='train_op')
else:
clones_losses = []
regularization_losses = tf.get_collection(
tf.GraphKeys.REGULARIZATION_LOSSES)
for clone in clones:
with tf.name_scope(clone.scope):
clone_loss = _gather_clone_loss(clone, len(clones),
regularization_losses)
if clone_loss is not None:
clones_losses.append(clone_loss)
# Only use regularization_losses for the first clone
regularization_losses = None
if clones_losses:
total_loss = tf.add_n(clones_losses, name='total_loss')
# Add the summaries from the first clone. These contain the summaries
# created by model_fn and either optimize_clones() or _gather_clone_loss().
summaries |= set(tf.get_collection(tf.GraphKeys.SUMMARIES,
first_clone.scope))
if total_loss is not None:
# Add total_loss to summary.
summaries.add(tf.summary.scalar('total_loss', total_loss))
if summaries:
# Merge all summaries together.
summary_op = tf.summary.merge(list(summaries), name='summary_op')
else:
summary_op = None
return DeployedModel(train_op, summary_op, total_loss, clones)
def _sum_clones_gradients(clone_grads):
"""Calculate the sum gradient for each shared variable across all clones.
This function assumes that the clone_grads has been scaled appropriately by
1 / num_clones.
Args:
clone_grads: A List of List of tuples (gradient, variable), one list per
`Clone`.
Returns:
List of tuples of (gradient, variable) where the gradient has been summed
across all clones.
"""
sum_grads = []
for grad_and_vars in zip(*clone_grads):
# Note that each grad_and_vars looks like the following:
# ((grad_var0_clone0, var0), ... (grad_varN_cloneN, varN))
grads = []
var = grad_and_vars[0][1]
for g, v in grad_and_vars:
assert v == var
if g is not None:
grads.append(g)
if grads:
if len(grads) > 1:
sum_grad = tf.add_n(grads, name=var.op.name + '/sum_grads')
else:
sum_grad = grads[0]
sum_grads.append((sum_grad, var))
return sum_grads
def _add_gradients_summaries(grads_and_vars):
"""Add histogram summaries to gradients.
Note: The summaries are also added to the SUMMARIES collection.
Args:
grads_and_vars: A list of gradient to variable pairs (tuples).
Returns:
The _list_ of the added summaries for grads_and_vars.
"""
summaries = []
for grad, var in grads_and_vars:
if grad is not None:
if isinstance(grad, tf.IndexedSlices):
grad_values = grad.values
else:
grad_values = grad
summaries.append(tf.summary.histogram(var.op.name + ':gradient',
grad_values))
summaries.append(tf.summary.histogram(var.op.name + ':gradient_norm',
tf.global_norm([grad_values])))
else:
tf.logging.info('Var %s has no gradient', var.op.name)
return summaries
class DeploymentConfig(object):
"""Configuration for deploying a model with `deploy()`.
You can pass an instance of this class to `deploy()` to specify exactly
how to deploy the model to build. If you do not pass one, an instance built
from the default deployment_hparams will be used.
"""
def __init__(self,
num_clones=1,
clone_on_cpu=False,
replica_id=0,
num_replicas=1,
num_ps_tasks=0,
worker_job_name='worker',
ps_job_name='ps'):
"""Create a DeploymentConfig.
The config describes how to deploy a model across multiple clones and
replicas. The model will be replicated `num_clones` times in each replica.
If `clone_on_cpu` is True, each clone will placed on CPU.
If `num_replicas` is 1, the model is deployed via a single process. In that
case `worker_device`, `num_ps_tasks`, and `ps_device` are ignored.
If `num_replicas` is greater than 1, then `worker_device` and `ps_device`
must specify TensorFlow devices for the `worker` and `ps` jobs and
`num_ps_tasks` must be positive.
Args:
num_clones: Number of model clones to deploy in each replica.
clone_on_cpu: If True clones would be placed on CPU.
replica_id: Integer. Index of the replica for which the model is
deployed. Usually 0 for the chief replica.
num_replicas: Number of replicas to use.
num_ps_tasks: Number of tasks for the `ps` job. 0 to not use replicas.
worker_job_name: A name for the worker job.
ps_job_name: A name for the parameter server job.
Raises:
ValueError: If the arguments are invalid.
"""
if num_replicas > 1:
if num_ps_tasks < 1:
raise ValueError('When using replicas num_ps_tasks must be positive')
if num_replicas > 1 or num_ps_tasks > 0:
if not worker_job_name:
raise ValueError('Must specify worker_job_name when using replicas')
if not ps_job_name:
raise ValueError('Must specify ps_job_name when using parameter server')
if replica_id >= num_replicas:
raise ValueError('replica_id must be less than num_replicas')
self._num_clones = num_clones
self._clone_on_cpu = clone_on_cpu
self._replica_id = replica_id
self._num_replicas = num_replicas
self._num_ps_tasks = num_ps_tasks
self._ps_device = '/job:' + ps_job_name if num_ps_tasks > 0 else ''
self._worker_device = '/job:' + worker_job_name if num_ps_tasks > 0 else ''
@property
def num_clones(self):
return self._num_clones
@property
def clone_on_cpu(self):
return self._clone_on_cpu
@property
def replica_id(self):
return self._replica_id
@property
def num_replicas(self):
return self._num_replicas
@property
def num_ps_tasks(self):
return self._num_ps_tasks
@property
def ps_device(self):
return self._ps_device
@property
def worker_device(self):
return self._worker_device
def caching_device(self):
"""Returns the device to use for caching variables.
Variables are cached on the worker CPU when using replicas.
Returns:
A device string or None if the variables do not need to be cached.
"""
if self._num_ps_tasks > 0:
return lambda op: op.device
else:
return None
def clone_device(self, clone_index):
"""Device used to create the clone and all the ops inside the clone.
Args:
clone_index: Int, representing the clone_index.
Returns:
A value suitable for `tf.device()`.
Raises:
ValueError: if `clone_index` is greater or equal to the number of clones".
"""
if clone_index >= self._num_clones:
raise ValueError('clone_index must be less than num_clones')
device = ''
if self._num_ps_tasks > 0:
device += self._worker_device
if self._clone_on_cpu:
device += '/device:CPU:0'
else:
device += '/device:GPU:%d' % clone_index
return device
def clone_scope(self, clone_index):
"""Name scope to create the clone.
Args:
clone_index: Int, representing the clone_index.
Returns:
A name_scope suitable for `tf.name_scope()`.
Raises:
ValueError: if `clone_index` is greater or equal to the number of clones".
"""
if clone_index >= self._num_clones:
raise ValueError('clone_index must be less than num_clones')
scope = ''
if self._num_clones > 1:
scope = 'clone_%d' % clone_index
return scope
def optimizer_device(self):
"""Device to use with the optimizer.
Returns:
A value suitable for `tf.device()`.
"""
if self._num_ps_tasks > 0 or self._num_clones > 0:
return self._worker_device + '/device:CPU:0'
else:
return ''
def inputs_device(self):
"""Device to use to build the inputs.
Returns:
A value suitable for `tf.device()`.
"""
device = ''
if self._num_ps_tasks > 0:
device += self._worker_device
device += '/device:CPU:0'
return device
def variables_device(self):
"""Returns the device to use for variables created inside the clone.
Returns:
A value suitable for `tf.device()`.
"""
device = ''
if self._num_ps_tasks > 0:
device += self._ps_device
device += '/device:CPU:0'
class _PSDeviceChooser(object):
"""Slim device chooser for variables when using PS."""
def __init__(self, device, tasks):
self._device = device
self._tasks = tasks
self._task = 0
def choose(self, op):
if op.device:
return op.device
node_def = op if isinstance(op, tf.NodeDef) else op.node_def
if node_def.op.startswith('Variable'):
t = self._task
self._task = (self._task + 1) % self._tasks
d = '%s/task:%d' % (self._device, t)
return d
else:
return op.device
if not self._num_ps_tasks:
return device
else:
chooser = _PSDeviceChooser(device, self._num_ps_tasks)
return chooser.choose
|
TensorFlow/Classification/ConvNets/se-resnext101-32x4d/training | training | DGX1_SE-RNxt101-32x4d_FP32_250E | #!/bin/bash
# Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
WORKSPACE=${1:-"/workspace/rn50v15_tf"}
DATA_DIR=${2:-"/data"}
OTHER=${@:3}
if [[ ! -z "${BIND_TO_SOCKET}" ]]; then
BIND_TO_SOCKET="--bind-to socket"
fi
mpiexec --allow-run-as-root ${BIND_TO_SOCKET} -np 8 python3 main.py --arch=se-resnext101-32x4d \
--mode=train_and_evaluate --iter_unit=epoch --num_iter=250 --mixup=0.2 \
--batch_size=64 --warmup_steps=100 --cosine_lr --label_smoothing 0.1 \
--lr_init=0.256 --lr_warmup_epochs=8 --momentum=0.875 --weight_decay=6.103515625e-05 \
--data_dir=${DATA_DIR}/tfrecords --data_idx_dir=${DATA_DIR}/dali_idx \
--results_dir=${WORKSPACE}/results --weight_init=fan_in ${OTHER}
|
TensorFlow2/LanguageModeling/BERT/official/utils/flags | flags | core | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Public interface for flag definition.
See _example.py for detailed instructions on defining flags.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from six.moves import shlex_quote
from absl import app as absl_app
from absl import flags
from official.utils.flags import _base
from official.utils.flags import _benchmark
from official.utils.flags import _conventions
from official.utils.flags import _device
from official.utils.flags import _distribution
from official.utils.flags import _misc
from official.utils.flags import _performance
def set_defaults(**kwargs):
for key, value in kwargs.items():
flags.FLAGS.set_default(name=key, value=value)
def parse_flags(argv=None):
"""Reset flags and reparse. Currently only used in testing."""
flags.FLAGS.unparse_flags()
absl_app.parse_flags_with_usage(argv or sys.argv)
def register_key_flags_in_core(f):
"""Defines a function in core.py, and registers its key flags.
absl uses the location of a flags.declare_key_flag() to determine the context
in which a flag is key. By making all declares in core, this allows model
main functions to call flags.adopt_module_key_flags() on core and correctly
chain key flags.
Args:
f: The function to be wrapped
Returns:
The "core-defined" version of the input function.
"""
def core_fn(*args, **kwargs):
key_flags = f(*args, **kwargs)
[flags.declare_key_flag(fl) for fl in key_flags] # pylint: disable=expression-not-assigned
return core_fn
define_base = register_key_flags_in_core(_base.define_base)
# We have define_base_eager for compatibility, since it used to be a separate
# function from define_base.
define_base_eager = define_base
define_benchmark = register_key_flags_in_core(_benchmark.define_benchmark)
define_device = register_key_flags_in_core(_device.define_device)
define_image = register_key_flags_in_core(_misc.define_image)
define_performance = register_key_flags_in_core(_performance.define_performance)
define_distribution = register_key_flags_in_core(
_distribution.define_distribution)
help_wrap = _conventions.help_wrap
get_num_gpus = _base.get_num_gpus
get_tf_dtype = _performance.get_tf_dtype
get_loss_scale = _performance.get_loss_scale
DTYPE_MAP = _performance.DTYPE_MAP
require_cloud_storage = _device.require_cloud_storage
def _get_nondefault_flags_as_dict():
"""Returns the nondefault flags as a dict from flag name to value."""
nondefault_flags = {}
for flag_name in flags.FLAGS:
flag_value = getattr(flags.FLAGS, flag_name)
if (flag_name != flags.FLAGS[flag_name].short_name and
flag_value != flags.FLAGS[flag_name].default):
nondefault_flags[flag_name] = flag_value
return nondefault_flags
def get_nondefault_flags_as_str():
"""Returns flags as a string that can be passed as command line arguments.
E.g., returns: "--batch_size=256 --use_synthetic_data" for the following code
block:
```
flags.FLAGS.batch_size = 256
flags.FLAGS.use_synthetic_data = True
print(get_nondefault_flags_as_str())
```
Only flags with nondefault values are returned, as passing default flags as
command line arguments has no effect.
Returns:
A string with the flags, that can be passed as command line arguments to a
program to use the flags.
"""
nondefault_flags = _get_nondefault_flags_as_dict()
flag_strings = []
for name, value in sorted(nondefault_flags.items()):
if isinstance(value, bool):
flag_str = '--{}'.format(name) if value else '--no{}'.format(name)
elif isinstance(value, list):
flag_str = '--{}={}'.format(name, ','.join(value))
else:
flag_str = '--{}={}'.format(name, value)
flag_strings.append(flag_str)
return ' '.join(shlex_quote(flag_str) for flag_str in flag_strings)
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt/plugins/taco2AttentionPlugin | taco2AttentionPlugin | taco2AttentionLayerPluginCreator | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "taco2AttentionLayerPluginCreator.h"
#include "taco2AttentionLayerPlugin.h"
#include <stdexcept>
#include <vector>
using namespace nvinfer1;
namespace nvinfer1
{
namespace plugin
{
/******************************************************************************
* CONSTANTS ******************************************************************
*****************************************************************************/
namespace
{
constexpr const char* const ENCODING_DIMENSION_STR = "EncodingDimension";
constexpr const char* const QUERY_DIMENSION_STR = "QueryDimension";
constexpr const char* const NUM_FILTERS_STR = "NumFilters";
constexpr const char* const CONV_KERNEL_SIZE_STR = "ConvKernelSize";
constexpr const char* const ATTENTION_DIMENSION_STR = "AttentionDimension";
constexpr const char* const QUERY_WEIGHTS_STR = "QueryWeight";
constexpr const char* const CONV_WEIGHTS_STR = "ConvWeight";
constexpr const char* const LOCATION_WEIGHTS_STR = "LocationWeight";
constexpr const char* const ENERGY_WEIGHTS_STR = "EnergyWeight";
} // namespace
/******************************************************************************
* PUBLIC STATIC METHODS ******************************************************
*****************************************************************************/
PluginFieldCollection* Taco2AttentionLayerPluginCreator::getFields()
{
static PluginFieldCollection* pluginPtr = nullptr;
static const std::vector<PluginField> fields{
{ENCODING_DIMENSION_STR, nullptr, PluginFieldType::kINT32, 0},
{QUERY_DIMENSION_STR, nullptr, PluginFieldType::kINT32, 0},
{NUM_FILTERS_STR, nullptr, PluginFieldType::kINT32, 0},
{CONV_KERNEL_SIZE_STR, nullptr, PluginFieldType::kINT32, 0},
{ATTENTION_DIMENSION_STR, nullptr, PluginFieldType::kINT32, 0},
{QUERY_WEIGHTS_STR, nullptr, PluginFieldType::kFLOAT32, 0},
{CONV_WEIGHTS_STR, nullptr, PluginFieldType::kFLOAT32, 0},
{LOCATION_WEIGHTS_STR, nullptr, PluginFieldType::kFLOAT32, 0},
{ENERGY_WEIGHTS_STR, nullptr, PluginFieldType::kFLOAT32, 0}};
if (!pluginPtr)
{
pluginPtr
= static_cast<PluginFieldCollection*>(malloc(sizeof(*pluginPtr) + fields.size() * sizeof(PluginField)));
pluginPtr->nbFields = static_cast<int>(fields.size());
pluginPtr->fields = fields.data();
}
return pluginPtr;
}
/******************************************************************************
* CONSTRUCTORS / DESTRUCTOR **************************************************
*****************************************************************************/
Taco2AttentionLayerPluginCreator::Taco2AttentionLayerPluginCreator()
: mNamespace()
{
// do nothing
}
/******************************************************************************
* PUBLIC METHODS *************************************************************
*****************************************************************************/
const char* Taco2AttentionLayerPluginCreator::getPluginName() const
{
return Taco2AttentionLayerPlugin::getName();
}
const char* Taco2AttentionLayerPluginCreator::getPluginVersion() const
{
return Taco2AttentionLayerPlugin::getVersion();
}
const PluginFieldCollection* Taco2AttentionLayerPluginCreator::getFieldNames()
{
return getFields();
}
IPluginV2* Taco2AttentionLayerPluginCreator::createPlugin(const char* const /*name*/, const PluginFieldCollection* fc)
{
int encDimension = 0;
int queryDimension = 0;
int numFilters = 0;
int convKernelSize = 0;
int attDimension = 0;
Weights queryWeights{DataType::kFLOAT, nullptr, 0};
Weights locationWeights{DataType::kFLOAT, nullptr, 0};
Weights convWeights{DataType::kFLOAT, nullptr, 0};
Weights energyWeights{DataType::kFLOAT, nullptr, 0};
for (int i = 0; i < fc->nbFields; ++i)
{
const std::string name(fc->fields[i].name);
if (name == ENCODING_DIMENSION_STR)
{
encDimension = static_cast<const int32_t*>(fc->fields[i].data)[0];
}
else if (name == QUERY_DIMENSION_STR)
{
queryDimension = static_cast<const int32_t*>(fc->fields[i].data)[0];
}
else if (name == NUM_FILTERS_STR)
{
numFilters = static_cast<const int32_t*>(fc->fields[i].data)[0];
}
else if (name == CONV_KERNEL_SIZE_STR)
{
convKernelSize = static_cast<const int32_t*>(fc->fields[i].data)[0];
}
else if (name == ATTENTION_DIMENSION_STR)
{
attDimension = static_cast<const int32_t*>(fc->fields[i].data)[0];
}
else if (name == QUERY_WEIGHTS_STR)
{
queryWeights.values = fc->fields[i].data;
queryWeights.count = fc->fields[i].length;
}
else if (name == CONV_WEIGHTS_STR)
{
convWeights.values = fc->fields[i].data;
convWeights.count = fc->fields[i].length;
}
else if (name == LOCATION_WEIGHTS_STR)
{
locationWeights.values = fc->fields[i].data;
locationWeights.count = fc->fields[i].length;
}
else if (name == ENERGY_WEIGHTS_STR)
{
energyWeights.values = fc->fields[i].data;
energyWeights.count = fc->fields[i].length;
}
else
{
throw std::runtime_error("Unknown plugin field: '" + name + "'");
}
}
return new Taco2AttentionLayerPlugin(encDimension, queryDimension, numFilters, convKernelSize, attDimension,
queryWeights, convWeights, locationWeights, energyWeights);
}
IPluginV2* Taco2AttentionLayerPluginCreator::deserializePlugin(
const char* const /* layerName */, const void* const serialData, size_t const serialLength)
{
return new Taco2AttentionLayerPlugin(Taco2AttentionLayerPlugin::deserialize(serialData, serialLength));
}
void Taco2AttentionLayerPluginCreator::setPluginNamespace(const char* pluginNamespace)
{
mNamespace = pluginNamespace;
}
const char* Taco2AttentionLayerPluginCreator::getPluginNamespace() const
{
return mNamespace.c_str();
}
} // namespace plugin
} // namespace nvinfer1
|
TensorFlow/Classification/ConvNets/triton | triton | rn50_model | import logging
import tensorflow as tf
from utils import data_utils
LOGGER = logging.getLogger(__name__)
NCLASSES = 1001
WIDTH = 224
HEIGHT = 224
NCHANNELS = 3
INPUT_FORMAT = "NHWC"
COMPUTE_FORMAT = "NHWC"
def get_model(
*,
model_dir: str,
arch: str = "resnet50",
precision: str = "fp32",
use_xla: bool = True,
use_tf_amp: bool = False,
use_dali: bool = False,
gpu_memory_fraction=0.7,
):
from runtime import Runner
from utils import hvd_wrapper as hvd
hvd.init()
try:
dtype = {"fp16": tf.float16, "fp32": tf.float32}[precision.lower()]
except KeyError:
raise ValueError(f"Uknown precision {precision}. Allowed values: fp16|fp32")
LOGGER.info(
f"Creating model arch={arch} precision={precision} xla={use_xla}"
f"tf_amp={use_tf_amp}, dali={use_dali}, gpu_memory_frac={gpu_memory_fraction}"
)
runner = Runner(
n_classes=NCLASSES,
architecture=arch,
input_format=INPUT_FORMAT,
compute_format=COMPUTE_FORMAT,
dtype=dtype,
n_channels=NCHANNELS,
height=HEIGHT,
width=WIDTH,
use_xla=use_xla,
use_tf_amp=use_tf_amp,
use_dali=use_dali,
gpu_memory_fraction=gpu_memory_fraction,
gpu_id=0,
model_dir=model_dir,
)
# removed params not used in inference
estimator_params = {"use_final_conv": False} # TODO: Why not moved to model constructor?
estimator = runner._get_estimator(
mode="inference",
run_params=estimator_params,
use_xla=use_xla,
use_dali=use_dali,
gpu_memory_fraction=gpu_memory_fraction,
)
return estimator
def get_serving_input_receiver_fn(
batch_size: int = None,
input_dtype: str = "fp32",
width: int = WIDTH,
height: int = HEIGHT,
nchannels: int = NCHANNELS,
):
input_dtype = tf.float16 if input_dtype and "16" in input_dtype else tf.float32
serving_input_receiver_fn = data_utils.get_serving_input_receiver_fn(
batch_size=batch_size,
height=height,
width=width,
num_channels=nchannels,
data_format=INPUT_FORMAT,
dtype=input_dtype,
)
return serving_input_receiver_fn
|
PaddlePaddle/LanguageModeling/BERT | BERT | optimizer | # Copyright (c) 2022 NVIDIA Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import logging
import paddle
from paddle import optimizer as optim
_EXCLUDE_FROM_DECAY = ["b_0", "norm"]
class AdamW:
"""
AdamW optimizer.
Args:
args(Namespace): Arguments obtained from ArgumentParser.
learning_rate(float|LRScheduler, optional): The learning rate used to update parameters. Default: 0.001
Can be a float value or a paddle.optimizer.lr.LRScheduler.
"""
def __init__(self, args, learning_rate):
self.learning_rate = learning_rate
self.beta1 = args.beta1
self.beta2 = args.beta2
self.epsilon = args.epsilon
self.weight_decay = args.weight_decay
self.multi_precision = args.amp
def __call__(self):
# not apply weight decay to all bias and layer_norm
def apply_decay_func(name):
return False if any(key in name
for key in _EXCLUDE_FROM_DECAY) else True
# add grad clipping to prevent exploding gradients
clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
opt = optim.AdamW(
learning_rate=self.learning_rate,
beta1=self.beta1,
beta2=self.beta2,
epsilon=self.epsilon,
weight_decay=self.weight_decay,
apply_decay_param_fun=apply_decay_func,
grad_clip=clip,
multi_precision=self.multi_precision)
return opt
class Lamb:
"""
Lamb optimizer.
Args:
args(Namespace): Arguments obtained from ArgumentParser.
learning_rate(float|LRScheduler, optional): The learning rate used to update parameters. Default: 0.001
Can be a float value or a paddle.optimizer.lr.LRScheduler.
"""
def __init__(self, args, learning_rate):
self.learning_rate = learning_rate
self.beta1 = args.beta1
self.beta2 = args.beta2
self.epsilon = args.epsilon
self.lamb_weight_decay = args.weight_decay
self.multi_precision = args.amp
def __call__(self):
# not apply weight decay to all bias and layer_norm
def exclude_from_decay_func(param):
return True if any(key in param.name
for key in _EXCLUDE_FROM_DECAY) else False
clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
opt = optim.Lamb(
learning_rate=self.learning_rate,
lamb_weight_decay=self.lamb_weight_decay,
beta1=self.beta1,
beta2=self.beta2,
epsilon=self.epsilon,
exclude_from_weight_decay_fn=exclude_from_decay_func,
grad_clip=clip)
opt._multi_precision = True if self.multi_precision else False
return opt
class DistributedFusedLamb:
"""
DistributedFusedLamb optimizer.
Args:
args(Namespace): Arguments obtained from ArgumentParser.
learning_rate(float|LRScheduler, optional): The learning rate used to update parameters. Default: 0.001
Can be a float value or a paddle.optimizer.lr.LRScheduler.
"""
def __init__(self, args, learning_rate):
self.learning_rate = learning_rate
self.beta1 = args.beta1
self.beta2 = args.beta2
self.epsilon = args.epsilon
self.lamb_weight_decay = args.weight_decay
self.gradient_merge_steps = args.gradient_merge_steps
def __call__(self):
# not apply weight decay to all bias and layer_norm
def exclude_from_decay_func(param):
return True if any(key in param.name
for key in _EXCLUDE_FROM_DECAY) else False
clip = paddle.nn.ClipGradByGlobalNorm(clip_norm=1.0)
opt = paddle.incubate.DistributedFusedLamb(
learning_rate=self.learning_rate,
lamb_weight_decay=self.lamb_weight_decay,
beta1=self.beta1,
beta2=self.beta2,
epsilon=self.epsilon,
exclude_from_weight_decay_fn=exclude_from_decay_func,
grad_clip=clip,
clip_after_allreduce=True,
is_grad_scaled_by_nranks=False,
use_master_param_norm=True,
gradient_accumulation_steps=self.gradient_merge_steps,
use_master_acc_grad=True)
return opt
def build_optimizer(args, lr):
"""
Build a raw optimizer with learning rate scheduler.
Args:
args(Namespace): Arguments obtained from ArgumentParser.
lr(paddle.optimizer.lr.LRScheduler): A LRScheduler used for training.
return:
optim(paddle.optimizer): A normal optmizer.
"""
optimizer_mod = sys.modules[__name__]
opt = getattr(optimizer_mod, args.optimizer)(args, learning_rate=lr)()
logging.info("build optimizer %s success..", opt)
return opt
|
TensorFlow2/LanguageModeling/BERT/data | data | WikicorpusTextFormatting | # Copyright (c) 2019 NVIDIA CORPORATION. All rights reserved.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import glob
import os
class WikicorpusTextFormatting:
def __init__(self, wiki_path, output_filename, recursive = False):
self.wiki_path = wiki_path
self.recursive = recursive
self.output_filename = output_filename
# This puts one article per line
def merge(self):
with open(self.output_filename, mode='w', newline='\n') as ofile:
for dirname in glob.glob(self.wiki_path + '/*/', recursive=False):
for filename in glob.glob(dirname + 'wiki_*', recursive=self.recursive):
print(filename)
article_lines = []
article_open = False
with open(filename, mode='r', newline='\n') as file:
for line in file:
if '<doc id=' in line:
article_open = True
elif '</doc>' in line:
article_open = False
for oline in article_lines[1:]:
if oline != '\n':
ofile.write(oline.rstrip() + " ")
ofile.write("\n\n")
article_lines = []
else:
if article_open:
article_lines.append(line) |
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt/tacotron2 | tacotron2 | tacotron2StreamingInstance | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "tacotron2StreamingInstance.h"
#include "checkedCopy.h"
#include "cudaUtils.h"
#include "dataShuffler.h"
#include "decoderInstancePlain.h"
#include "decoderInstancePlugins.h"
#include "encoderInstance.h"
#include "maskGenerator.h"
#include "postNetInstance.h"
#include "trtUtils.h"
#include "utils.h"
#include <cstdint>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
using namespace nvinfer1;
namespace tts
{
/******************************************************************************
* CONSTRUCTORS / DESTRUCTOR **************************************************
*****************************************************************************/
Tacotron2StreamingInstance::Tacotron2StreamingInstance(
TRTPtr<ICudaEngine> encoderEngine,
TRTPtr<ICudaEngine> decoderPlainEngine,
TRTPtr<ICudaEngine> decoderPluginsEngine,
TRTPtr<ICudaEngine> postnetEngine) :
TimedObject("Tacotron2StreamingInstance::infer()"),
mEncoder(std::make_shared<EncoderInstance>(std::move(encoderEngine))),
mDecoderPlain(
decoderPlainEngine
? std::make_shared<DecoderInstancePlain>(
std::move(decoderPlainEngine),
TRTUtils::getBindingDimension(
*postnetEngine, PostNetInstance::OUTPUT_NAME, 1))
: nullptr),
mDecoderPlugins(
decoderPluginsEngine
? std::make_shared<DecoderInstancePlugins>(
std::move(decoderPluginsEngine),
TRTUtils::getBindingDimension(
*postnetEngine, PostNetInstance::OUTPUT_NAME, 1))
: nullptr),
mPostnet(std::make_shared<PostNetInstance>(std::move(postnetEngine))),
mMaxInputLength(mEncoder->getInputLength()),
mNumMelChannels(mPostnet->getNumMelChannels()),
mNumMelChunks(mPostnet->getMelChunkSize()),
mMaxBatchSize(std::min(
mEncoder->getMaxBatchSize(),
std::min(
mDecoderPlain ? mDecoderPlain->getMaxBatchSize()
: mDecoderPlugins->getMaxBatchSize(),
mPostnet->getMaxBatchSize()))),
mBatchSize(0),
mUsePlugins(mDecoderPlugins),
mInUseDecoder(nullptr),
mPaddedInputDevice(mMaxBatchSize * mMaxInputLength),
mInputMaskDevice(mMaxBatchSize * mMaxInputLength),
mInputLengthsDevice(mMaxBatchSize),
mEncodingDevice(
mMaxBatchSize * mMaxInputLength * mEncoder->getNumDimensions()),
mProcessedEncodingDevice(
mMaxBatchSize * mMaxInputLength
* mEncoder->getNumProcessedDimensions()),
mMelChunkDevice(
mMaxBatchSize * mNumMelChannels * mPostnet->getMelChunkSize()),
mInputLengthHost(nullptr)
{
assert(mNumMelChannels == mPostnet->getNumMelChannels());
// build timing structure
addChild(mEncoder.get());
if (mDecoderPlain)
{
addChild(mDecoderPlain.get());
}
if (mDecoderPlugins)
{
addChild(mDecoderPlugins.get());
}
addChild(mPostnet.get());
}
/******************************************************************************
* PUBLIC METHODS *************************************************************
*****************************************************************************/
void Tacotron2StreamingInstance::startInference(
const int batchSize,
const int* const inputDevice,
const int inputSpacing,
const int* const inputLength,
cudaStream_t stream)
{
startTiming();
mBatchSize = batchSize;
mInputLengthHost = inputLength;
if (mBatchSize < 0 || mBatchSize > mMaxBatchSize)
{
throw std::runtime_error(
"Maximum batch size is " + std::to_string(mMaxBatchSize) + " but got " + std::to_string(mBatchSize) + ".");
}
for (int i = 0; i < mBatchSize; ++i)
{
if (mInputLengthHost[i] > mMaxInputLength)
{
throw std::runtime_error("Model not configured for lengths greater than " + std::to_string(mMaxInputLength)
+ ". Given " + std::to_string(mInputLengthHost[i]) + " for sequence " + std::to_string(i) + ".");
}
}
// copy input to padded location and set zeros
CudaUtils::zeroAsync(
mPaddedInputDevice.data(), mMaxInputLength * mBatchSize, stream);
for (int i = 0; i < mBatchSize; ++i)
{
const int offset = mMaxInputLength * i;
const int length = mInputLengthHost[i];
CheckedCopy::deviceToDeviceAsync(
mPaddedInputDevice.data() + offset,
inputDevice + (i * inputSpacing),
length,
stream);
}
CheckedCopy::hostToDeviceAsync(
mInputLengthsDevice.data(), mInputLengthHost, mBatchSize, stream);
MaskGenerator::generate(
mInputLengthsDevice.data(),
mMaxInputLength,
mBatchSize,
mInputMaskDevice.data(),
stream);
mEncoder->infer(
stream,
mBatchSize,
mPaddedInputDevice.data(),
mInputMaskDevice.data(),
mInputLengthsDevice.data(),
mEncodingDevice.data(),
mProcessedEncodingDevice.data());
// configure decoder
if (willUsePlugins(mBatchSize))
{
if (!mDecoderPlugins)
{
std::cerr << "This tacotron2 decoder engine with plugins is missing. "
"Do you need to rebuild the engine?"
<< std::endl;
throw std::runtime_error("Missing mDecoderPlugins engine");
}
mInUseDecoder = mDecoderPlugins.get();
}
else
{
if (!mDecoderPlain)
{
std::cerr << "This tacotron2 decoder engine without plugins is missing. "
"Do you need to rebuild the engine?"
<< std::endl;
throw std::runtime_error("Missing mDecoderPlain engine");
}
mInUseDecoder = mDecoderPlain.get();
}
mInUseDecoder->reset(stream);
stopTiming();
}
bool Tacotron2StreamingInstance::inferNext(
float* const outputDevice, int* const outputLength, cudaStream_t stream)
{
startTiming();
if (!mInUseDecoder)
{
throw std::runtime_error(
"Tacotron2StreamingInstance::inferNext() cannot "
"be called until Tacotron2StreamingInstance::startInference() is "
"called.");
}
else if (mBatchSize <= 0 || mBatchSize > mMaxBatchSize)
{
throw std::runtime_error(
"Tacotron2StreamingInstance::inferNext() has an "
"invalid batch size of "
+ std::to_string(mBatchSize)
+ " set. "
"This is an internal error.");
}
else if (!mInputLengthHost)
{
throw std::runtime_error("mInputLengthHost not set.");
}
// do decoding
mInUseDecoder->infer(
stream,
mBatchSize,
mEncodingDevice.data(),
mProcessedEncodingDevice.data(),
mInputMaskDevice.data(),
mInputLengthHost,
mInputLengthsDevice.data(),
mMelChunkDevice.data());
// call postnet
mPostnet->infer(stream, mBatchSize, mMelChunkDevice.data(), outputDevice);
cudaStreamSynchronize(stream);
for (int batchIndex = 0; batchIndex < mBatchSize; ++batchIndex)
{
outputLength[batchIndex] = mInUseDecoder->lastChunkSize()[batchIndex];
}
stopTiming();
return !mInUseDecoder->isAllDone();
}
void Tacotron2StreamingInstance::setSeed(const unsigned int seed)
{
if (mDecoderPlain)
{
mDecoderPlain->setSeed(seed);
}
if (mDecoderPlugins)
{
mDecoderPlugins->setSeed(seed);
}
resetInference();
}
int Tacotron2StreamingInstance::getNumMelChannels() const
{
return mNumMelChannels;
}
int Tacotron2StreamingInstance::getChunkSize() const
{
return mNumMelChunks;
}
int Tacotron2StreamingInstance::getMaximumInputLength() const
{
return mMaxInputLength;
}
int Tacotron2StreamingInstance::getMaxBatchSize() const
{
return mMaxBatchSize;
}
void Tacotron2StreamingInstance::usePlugins(const bool usePlugins)
{
if (mDecoderPlugins)
{
mUsePlugins = usePlugins;
}
else
{
throw std::runtime_error(
"Cannot enable plugins. No plugin engine "
"available for use.");
}
resetInference();
}
bool Tacotron2StreamingInstance::willUsePlugins(const int batchSize) const
{
return mUsePlugins && mDecoderPlugins && batchSize <= mDecoderPlugins->getMaxBatchSize();
}
void Tacotron2StreamingInstance::setNextChunkSize(const int chunkSize)
{
if (!mInUseDecoder)
{
throw std::runtime_error(
"Cannot set next chunk size until "
"Tacotron2StreamingInstance::startInference() has been called.");
}
else if (chunkSize <= 0 || chunkSize > getChunkSize())
{
throw std::runtime_error("Invalid chunk size of " + std::to_string(chunkSize)
+ " passed to Tacotron2StreamingInstance::setNextChunkSize().");
}
mInUseDecoder->setNextChunkSize(chunkSize);
}
/******************************************************************************
* PRIVATE METHODS ************************************************************
*****************************************************************************/
void Tacotron2StreamingInstance::resetInference()
{
mInUseDecoder = nullptr;
mBatchSize = 0;
}
} // namespace tts
|
TensorFlow2/Classification/ConvNets/utils | utils | learning_rate | # Lint as: python3
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Learning rate utilities for vision tasks."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Any, List, Mapping
import tensorflow as tf
BASE_LEARNING_RATE = 0.1
__all__ = [ 'WarmupDecaySchedule', 'PiecewiseConstantDecayWithWarmup' ]
@tf.keras.utils.register_keras_serializable(package='Custom')
class WarmupDecaySchedule(tf.keras.optimizers.schedules.LearningRateSchedule):
"""A wrapper for LearningRateSchedule that includes warmup steps."""
def __init__(
self,
lr_schedule: tf.keras.optimizers.schedules.LearningRateSchedule,
warmup_steps: int,
**kwargs):
"""Add warmup decay to a learning rate schedule.
Args:
lr_schedule: base learning rate scheduler
warmup_steps: number of warmup steps
"""
super(WarmupDecaySchedule, self).__init__()
self._lr_schedule = lr_schedule
self._warmup_steps = warmup_steps
def __call__(self, step: int):
lr = self._lr_schedule(step)
if self._warmup_steps:
step_decay = step - self._warmup_steps
lr = self._lr_schedule(step_decay)
initial_learning_rate = tf.convert_to_tensor(
self._lr_schedule.initial_learning_rate, name="initial_learning_rate")
dtype = initial_learning_rate.dtype
global_step_recomp = tf.cast(step, dtype)
warmup_steps = tf.cast(self._warmup_steps, dtype)
warmup_lr = initial_learning_rate * global_step_recomp / warmup_steps
lr = tf.cond(global_step_recomp < warmup_steps,
lambda: warmup_lr,
lambda: lr)
return lr
def get_config(self) -> Mapping[str, Any]:
config = self._lr_schedule.get_config()
config.update({
"warmup_steps": self._warmup_steps,
})
config.update({
"lr_schedule": self._lr_schedule,
})
return config
# TODO(b/149030439) - refactor this with
# tf.keras.optimizers.schedules.PiecewiseConstantDecay + WarmupDecaySchedule.
class PiecewiseConstantDecayWithWarmup(
tf.keras.optimizers.schedules.LearningRateSchedule):
"""Piecewise constant decay with warmup schedule."""
def __init__(self,
batch_size: int,
epoch_size: int,
warmup_epochs: int,
boundaries: List[int],
multipliers: List[float]):
"""Piecewise constant decay with warmup.
Args:
batch_size: The training batch size used in the experiment.
epoch_size: The size of an epoch, or the number of examples in an epoch.
warmup_epochs: The number of warmup epochs to apply.
boundaries: The list of floats with strictly increasing entries.
multipliers: The list of multipliers/learning rates to use for the
piecewise portion. The length must be 1 less than that of boundaries.
"""
super(PiecewiseConstantDecayWithWarmup, self).__init__()
if len(boundaries) != len(multipliers) - 1:
raise ValueError("The length of boundaries must be 1 less than the "
"length of multipliers")
base_lr_batch_size = 256
steps_per_epoch = epoch_size // batch_size
self._rescaled_lr = BASE_LEARNING_RATE * batch_size / base_lr_batch_size
self._step_boundaries = [float(steps_per_epoch) * x for x in boundaries]
self._lr_values = [self._rescaled_lr * m for m in multipliers]
self._warmup_steps = warmup_epochs * steps_per_epoch
def __call__(self, step: int):
"""Compute learning rate at given step."""
def warmup_lr():
return self._rescaled_lr * (
step / tf.cast(self._warmup_steps, tf.float32))
def piecewise_lr():
return tf.compat.v1.train.piecewise_constant(
tf.cast(step, tf.float32), self._step_boundaries, self._lr_values)
return tf.cond(step < self._warmup_steps, warmup_lr, piecewise_lr)
def get_config(self) -> Mapping[str, Any]:
return {
"rescaled_lr": self._rescaled_lr,
"step_boundaries": self._step_boundaries,
"lr_values": self._lr_values,
"warmup_steps": self._warmup_steps,
}
|
PyTorch/LanguageModeling/BERT/triton/dist6l/runner | runner | start_NVIDIA-DGX-A100-(1x-A100-80GB) | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#!/bin/bash
# Install Docker
. /etc/os-release && \
curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add - && \
echo "deb [arch=amd64] https://download.docker.com/linux/debian buster stable" > /etc/apt/sources.list.d/docker.list && \
curl -s -L https://nvidia.github.io/nvidia-docker/gpgkey| apt-key add - && \
curl -s -L https://nvidia.github.io/nvidia-docker/$ID$VERSION_ID/nvidia-docker.list > /etc/apt/sources.list.d/nvidia-docker.list && \
apt-get update && \
apt-get install -y docker-ce docker-ce-cli containerd.io nvidia-docker2
# Install packages
pip install -r triton/runner/requirements.txt
# Evaluate Runner
python3 -m "triton.dist6l.runner.__main__" \
--config-path "triton/dist6l/runner/config_NVIDIA-DGX-A100-(1x-A100-80GB).yaml" \
--device 0 |
TensorFlow/LanguageModeling/BERT | BERT | run_classifier_with_tfhub | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""BERT finetuning runner with TF-Hub."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import optimization
import run_classifier
import tokenization
import tensorflow as tf
import tensorflow_hub as hub
flags = tf.flags
FLAGS = flags.FLAGS
flags.DEFINE_string(
"bert_hub_module_handle", None,
"Handle for the BERT TF-Hub module.")
def create_model(is_training, input_ids, input_mask, segment_ids, labels,
num_labels, bert_hub_module_handle):
"""Creates a classification model."""
tags = set()
if is_training:
tags.add("train")
bert_module = hub.Module(bert_hub_module_handle, tags=tags, trainable=True)
bert_inputs = dict(
input_ids=input_ids,
input_mask=input_mask,
segment_ids=segment_ids)
bert_outputs = bert_module(
inputs=bert_inputs,
signature="tokens",
as_dict=True)
# In the demo, we are doing a simple classification task on the entire
# segment.
#
# If you want to use the token-level output, use
# bert_outputs["sequence_output"] instead.
output_layer = bert_outputs["pooled_output"]
hidden_size = output_layer.shape[-1].value
output_weights = tf.get_variable(
"output_weights", [num_labels, hidden_size],
initializer=tf.truncated_normal_initializer(stddev=0.02))
output_bias = tf.get_variable(
"output_bias", [num_labels], initializer=tf.zeros_initializer())
with tf.variable_scope("loss"):
if is_training:
# I.e., 0.1 dropout
output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)
logits = tf.matmul(output_layer, output_weights, transpose_b=True)
logits = tf.nn.bias_add(logits, output_bias)
probabilities = tf.nn.softmax(logits, axis=-1)
log_probs = tf.nn.log_softmax(logits, axis=-1)
one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)
per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)
loss = tf.reduce_mean(per_example_loss)
return (loss, per_example_loss, logits, probabilities)
def model_fn_builder(num_labels, learning_rate, num_train_steps,
num_warmup_steps, use_tpu, bert_hub_module_handle):
"""Returns `model_fn` closure for TPUEstimator."""
def model_fn(features, labels, mode, params): # pylint: disable=unused-argument
"""The `model_fn` for TPUEstimator."""
tf.logging.info("*** Features ***")
for name in sorted(features.keys()):
tf.logging.info(" name = %s, shape = %s" % (name, features[name].shape))
input_ids = features["input_ids"]
input_mask = features["input_mask"]
segment_ids = features["segment_ids"]
label_ids = features["label_ids"]
is_training = (mode == tf.estimator.ModeKeys.TRAIN)
(total_loss, per_example_loss, logits, probabilities) = create_model(
is_training, input_ids, input_mask, segment_ids, label_ids, num_labels,
bert_hub_module_handle)
output_spec = None
if mode == tf.estimator.ModeKeys.TRAIN:
train_op = optimization.create_optimizer(
total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
train_op=train_op)
elif mode == tf.estimator.ModeKeys.EVAL:
def metric_fn(per_example_loss, label_ids, logits):
predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)
accuracy = tf.metrics.accuracy(label_ids, predictions)
loss = tf.metrics.mean(per_example_loss)
return {
"eval_accuracy": accuracy,
"eval_loss": loss,
}
eval_metrics = (metric_fn, [per_example_loss, label_ids, logits])
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode,
loss=total_loss,
eval_metrics=eval_metrics)
elif mode == tf.estimator.ModeKeys.PREDICT:
output_spec = tf.contrib.tpu.TPUEstimatorSpec(
mode=mode, predictions={"probabilities": probabilities})
else:
raise ValueError(
"Only TRAIN, EVAL and PREDICT modes are supported: %s" % (mode))
return output_spec
return model_fn
def create_tokenizer_from_hub_module(bert_hub_module_handle):
"""Get the vocab file and casing info from the Hub module."""
with tf.Graph().as_default():
bert_module = hub.Module(bert_hub_module_handle)
tokenization_info = bert_module(signature="tokenization_info", as_dict=True)
with tf.Session() as sess:
vocab_file, do_lower_case = sess.run([tokenization_info["vocab_file"],
tokenization_info["do_lower_case"]])
return tokenization.FullTokenizer(
vocab_file=vocab_file, do_lower_case=do_lower_case)
def main(_):
tf.logging.set_verbosity(tf.logging.INFO)
processors = {
"cola": run_classifier.ColaProcessor,
"mnli": run_classifier.MnliProcessor,
"mrpc": run_classifier.MrpcProcessor,
}
if not FLAGS.do_train and not FLAGS.do_eval:
raise ValueError("At least one of `do_train` or `do_eval` must be True.")
tf.gfile.MakeDirs(FLAGS.output_dir)
task_name = FLAGS.task_name.lower()
if task_name not in processors:
raise ValueError("Task not found: %s" % (task_name))
processor = processors[task_name]()
label_list = processor.get_labels()
tokenizer = create_tokenizer_from_hub_module(FLAGS.bert_hub_module_handle)
tpu_cluster_resolver = None
if FLAGS.use_tpu and FLAGS.tpu_name:
tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(
FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)
is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2
run_config = tf.contrib.tpu.RunConfig(
cluster=tpu_cluster_resolver,
master=FLAGS.master,
model_dir=FLAGS.output_dir,
save_checkpoints_steps=FLAGS.save_checkpoints_steps,
tpu_config=tf.contrib.tpu.TPUConfig(
iterations_per_loop=FLAGS.iterations_per_loop,
num_shards=FLAGS.num_tpu_cores,
per_host_input_for_training=is_per_host))
train_examples = None
num_train_steps = None
num_warmup_steps = None
if FLAGS.do_train:
train_examples = processor.get_train_examples(FLAGS.data_dir)
num_train_steps = int(
len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)
num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)
model_fn = model_fn_builder(
num_labels=len(label_list),
learning_rate=FLAGS.learning_rate,
num_train_steps=num_train_steps,
num_warmup_steps=num_warmup_steps,
use_tpu=FLAGS.use_tpu,
bert_hub_module_handle=FLAGS.bert_hub_module_handle)
# If TPU is not available, this will fall back to normal Estimator on CPU
# or GPU.
estimator = tf.contrib.tpu.TPUEstimator(
use_tpu=FLAGS.use_tpu,
model_fn=model_fn,
config=run_config,
train_batch_size=FLAGS.train_batch_size,
eval_batch_size=FLAGS.eval_batch_size,
predict_batch_size=FLAGS.predict_batch_size)
if FLAGS.do_train:
train_features = run_classifier.convert_examples_to_features(
train_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running training *****")
tf.logging.info(" Num examples = %d", len(train_examples))
tf.logging.info(" Batch size = %d", FLAGS.train_batch_size)
tf.logging.info(" Num steps = %d", num_train_steps)
train_input_fn = run_classifier.input_fn_builder(
features=train_features,
seq_length=FLAGS.max_seq_length,
is_training=True,
drop_remainder=True)
estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)
if FLAGS.do_eval:
eval_examples = processor.get_dev_examples(FLAGS.data_dir)
eval_features = run_classifier.convert_examples_to_features(
eval_examples, label_list, FLAGS.max_seq_length, tokenizer)
tf.logging.info("***** Running evaluation *****")
tf.logging.info(" Num examples = %d", len(eval_examples))
tf.logging.info(" Batch size = %d", FLAGS.eval_batch_size)
# This tells the estimator to run through the entire set.
eval_steps = None
# However, if running eval on the TPU, you will need to specify the
# number of steps.
if FLAGS.use_tpu:
# Eval will be slightly WRONG on the TPU because it will truncate
# the last batch.
eval_steps = int(len(eval_examples) / FLAGS.eval_batch_size)
eval_drop_remainder = True if FLAGS.use_tpu else False
eval_input_fn = run_classifier.input_fn_builder(
features=eval_features,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=eval_drop_remainder)
result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)
output_eval_file = os.path.join(FLAGS.output_dir, "eval_results.txt")
with tf.gfile.GFile(output_eval_file, "w") as writer:
tf.logging.info("***** Eval results *****")
for key in sorted(result.keys()):
tf.logging.info(" %s = %s", key, str(result[key]))
writer.write("%s = %s\n" % (key, str(result[key])))
if FLAGS.do_predict:
predict_examples = processor.get_test_examples(FLAGS.data_dir)
if FLAGS.use_tpu:
# Discard batch remainder if running on TPU
n = len(predict_examples)
predict_examples = predict_examples[:(n - n % FLAGS.predict_batch_size)]
predict_file = os.path.join(FLAGS.output_dir, "predict.tf_record")
run_classifier.file_based_convert_examples_to_features(
predict_examples, label_list, FLAGS.max_seq_length, tokenizer,
predict_file)
tf.logging.info("***** Running prediction*****")
tf.logging.info(" Num examples = %d", len(predict_examples))
tf.logging.info(" Batch size = %d", FLAGS.predict_batch_size)
predict_input_fn = run_classifier.file_based_input_fn_builder(
input_file=predict_file,
seq_length=FLAGS.max_seq_length,
is_training=False,
drop_remainder=FLAGS.use_tpu)
result = estimator.predict(input_fn=predict_input_fn)
output_predict_file = os.path.join(FLAGS.output_dir, "test_results.tsv")
with tf.gfile.GFile(output_predict_file, "w") as writer:
tf.logging.info("***** Predict results *****")
for prediction in result:
probabilities = prediction["probabilities"]
output_line = "\t".join(
str(class_probability)
for class_probability in probabilities) + "\n"
writer.write(output_line)
if __name__ == "__main__":
flags.mark_flag_as_required("data_dir")
flags.mark_flag_as_required("task_name")
flags.mark_flag_as_required("bert_hub_module_handle")
flags.mark_flag_as_required("output_dir")
tf.app.run()
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt | trt | speechSynthesizer | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TT2I_SPEECHSYNTHESIZER_H
#define TT2I_SPEECHSYNTHESIZER_H
#include "denoiserInstance.h"
#include "speechDataBuffer.h"
#include "tacotron2Instance.h"
#include "timedObject.h"
#include "waveGlowInstance.h"
#include <memory>
namespace tts
{
class SpeechSynthesizer : public virtual TimedObject
{
public:
SpeechSynthesizer(std::shared_ptr<Tacotron2Instance> tacotron, std::shared_ptr<WaveGlowInstance> waveglow);
SpeechSynthesizer(std::shared_ptr<Tacotron2Instance> tacotron, std::shared_ptr<WaveGlowInstance> waveglow,
std::shared_ptr<DenoiserInstance> denoiser);
SpeechSynthesizer(const SpeechSynthesizer& other) = delete;
SpeechSynthesizer& operator=(const SpeechSynthesizer& other) = delete;
/**
* @brief Perform inference in order to generate audio.
*
* @param batchSize The size of the batch to run.
* @param inputDevice The input sequences.
* @param inputSpacing The spacing between the start of each input sequence
* in the batch.
* @param inputLength The length of each input sequence.
* @param samplesDevice The samples of audio to generate. This must be of
* length equal to the batchSize times the return of `getMaxOutputSize()`
* (output).
* @param numSamples The number of samples in each audio segment (output).
* @param outputMelsDevice The mels to output on the device (optional).
* @param outputNumMels The number of mels generated (optional).
*/
void infer(int batchSize, const int* inputDevice, int inputSpacing, const int* inputLength, float* samplesDevice,
int* numSamples, float* outputMelsDevice = nullptr, int* outputNumMels = nullptr);
/**
* @brief Perform inference in order to generate audio, but taking inputs
* from host memory.
*
* @param batchSize The size of the batch to run.
* @param inputHost The input sequences.
* @param inputSpacing The spacing between the start of each input sequence
* in the batch.
* @param inputLength The length of each input sequence.
* @param samplesHost The samples of audio to generate. This must be of
* length equal to the batchSize times the return of `getMaxOutputSize()`
* (output).
* @param numSamples The number of samples in each audio segment (output).
* @param outputMelsHost The mels to output optional).
* @param outputNumMels The number of mels generated (optional).
*/
void inferFromHost(int batchSize, const int* inputHost, int inputSpacing, const int* inputLength,
float* samplesHost, int* numSamples, float* outputMelsHost = nullptr, int* outputNumMels = nullptr);
/**
* @brief Perform inference in order to generate audio, but taking inputs
* from host memory.
*
* @param batchSize The size of the batch to run.
* @param inputHost The input sequences (must be of length batchSize).
* @param outputHost The samples of audio to generate (must be of length
* batchSize).
*/
void inferFromHost(int batchSize, const std::vector<int32_t>* inputHost, std::vector<float>* outputHost);
/**
* @brief Get the maximum batch size that can be ran.
*
* @return The maximum batch size.
*/
int getMaxBatchSize() const;
/**
* @brief Get the maximum input size for each item in the batch.
*
* @return The maximum input size.
*/
int getMaxInputSize() const;
/**
* @brief Get the maximum number of samples that will be returned for each
* item in the batch.
*
* @return The maximum output size.
*/
int getMaxOutputSize() const;
/**
* @brief Get the spacing in frames between the start of mel-spectrogram
* sequences in batches.
*
* @return The spacing in frames.
*/
int getMelSpacing() const;
private:
int mMaxBatchSize;
int mNumMaxMels;
std::vector<int> mNumSymbols;
std::vector<int> mNumFrames;
std::vector<int> mNumSamples;
std::shared_ptr<Tacotron2Instance> mTacotron;
std::shared_ptr<WaveGlowInstance> mWaveglow;
std::shared_ptr<DenoiserInstance> mDenoiser;
SpeechDataBuffer mBuffer;
};
} // namespace tts
#endif
|
Tools/DGLPyTorch/SyntheticGraphGeneration/syngen/benchmark/data_loader/datasets | datasets | edge_ds | # Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Optional
import dgl
import numpy as np
import torch
from syngen.configuration import SynGenDatasetFeatureSpec
from syngen.utils.types import DataFrameType, MetaData
from .base_dataset import BaseDataset
class EdgeDS(BaseDataset):
"""
lean DGL graph builder for edge classification,
"""
def __init__(
self,
target_col: str = "label",
add_reverse: bool = True,
train_ratio: float = 0.8,
test_ratio: float = 0.1,
val_ratio: float = 0.1,
**kwargs,
):
self.target_col = target_col
self.add_reverse = add_reverse
self.train_ratio = train_ratio
self.test_ratio = test_ratio
self.val_ratio = val_ratio
def get_graph(
self,
feature_spec: SynGenDatasetFeatureSpec,
edge_name
):
struct_data = feature_spec.get_structural_data(edge_name)
edge_info = feature_spec.get_edge_info(edge_name)
is_bipartite = edge_info[MetaData.SRC_NODE_TYPE] != edge_info[MetaData.DST_NODE_TYPE]
if is_bipartite:
offset = struct_data[:, 0].max() + 16
struct_data[:, 1] = struct_data[:, 1] + offset
# - construct dgl graph
g = dgl.graph((struct_data[:, 0], struct_data[:, 1]))
g.ndata["feat"] = torch.rand((g.num_nodes(), 32))
assert g.num_nodes() == (struct_data.max() + 1), f"expected {(struct_data.max() + 1)}, got {g.num_nodes()}"
if self.add_reverse:
edge_reverse = np.zeros_like(struct_data)
edge_reverse[:, 0] = struct_data[:, 1]
edge_reverse[:, 1] = struct_data[:, 0]
g.add_edges(edge_reverse[:, 0], edge_reverse[:, 1])
edge_data = feature_spec.get_tabular_data(MetaData.EDGES, edge_name)
feature_cols = list(set(edge_data.columns) - {self.target_col})
num_rows = len(edge_data)
num_edges = g.num_edges()
# - extract edge features + labels
features = edge_data[feature_cols].astype(np.float32).values
labels = edge_data[self.target_col].fillna(0).astype(np.float32).values
if num_rows == num_edges // 2:
# - add reverse features
features = np.concatenate([features, features], axis=0)
# - add reverse labels
labels = np.concatenate([labels, labels], axis=0)
# - add edge data
g.edata["feat"] = torch.Tensor(features)
g.edata["labels"] = torch.Tensor(labels)
# - dataset split
num_train = int(self.train_ratio * num_edges)
num_val = int(self.val_ratio * num_edges)
num_test = int(self.test_ratio * num_edges)
masks = torch.randperm(len(features))
train_idx = masks[:num_train]
val_idx = masks[num_train : num_train + num_val]
test_idx = masks[num_train + num_val : num_train + num_val + num_test]
train_mask = torch.zeros(len(features), dtype=torch.bool)
train_mask[train_idx] = True
val_mask = torch.zeros(len(features), dtype=torch.bool)
val_mask[val_idx] = True
test_mask = torch.zeros(len(features), dtype=torch.bool)
test_mask[test_idx] = True
g.edata["train_mask"] = train_mask
g.edata["val_mask"] = val_mask
g.edata["test_mask"] = test_mask
edge_eids = np.arange(0, len(struct_data))
return g, edge_eids
|
TensorFlow/Recommendation/NCF | NCF | load | # Copyright (c) 2018, deepakn94. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from collections import namedtuple
import pandas as pd
RatingData = namedtuple('RatingData',
['items', 'users', 'ratings', 'min_date', 'max_date'])
def describe_ratings(ratings):
info = RatingData(items=len(ratings['item_id'].unique()),
users=len(ratings['user_id'].unique()),
ratings=len(ratings),
min_date=ratings['timestamp'].min(),
max_date=ratings['timestamp'].max())
print("{ratings} ratings on {items} items from {users} users"
" from {min_date} to {max_date}"
.format(**(info._asdict())))
return info
def process_movielens(ratings, sort=True):
ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s')
if sort:
ratings.sort_values(by='timestamp', inplace=True)
describe_ratings(ratings)
return ratings
def load_ml_1m(filename, sort=True):
names = ['user_id', 'item_id', 'rating', 'timestamp']
ratings = pd.read_csv(filename, sep='::', names=names, engine='python')
return process_movielens(ratings, sort=sort)
def load_ml_20m(filename, sort=True):
ratings = pd.read_csv(filename)
ratings['timestamp'] = pd.to_datetime(ratings['timestamp'], unit='s')
names = {'userId': 'user_id', 'movieId': 'item_id'}
ratings.rename(columns=names, inplace=True)
return process_movielens(ratings, sort=sort)
DATASETS = [k.replace('load_', '') for k in locals().keys() if "load_" in k]
def get_dataset_name(filename):
for dataset in DATASETS:
if dataset in filename.replace('-', '_').lower():
return dataset
raise NotImplementedError
def implicit_load(filename, sort=True):
func = globals()["load_" + get_dataset_name(filename)]
return func(filename, sort=sort)
|
PyTorch/Forecasting/TFT/triton/runner | runner | triton | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pathlib
# method from PEP-366 to support relative import in executed modules
if __name__ == "__main__" and __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .core import Framework, Paths
class Triton:
"""
Triton Inference Server helper class
"""
image = "nvcr.io/nvidia/tritonserver"
tag = "py3"
class LOAD_MODE:
"""
Loading mode available in Triton
"""
POLL = "poll"
EXPLICIT = "explicit"
@staticmethod
def container_image(container_version: str):
"""
Container image based on version
Args:
container_version: Version of container to be used
Returns:
Image name with tag
"""
return f"{Triton.image}:{container_version}-{Triton.tag}"
@staticmethod
def command(
framework: str,
repository_path: str,
strict_mode: bool = False,
poll_model: bool = False,
metrics: bool = False,
verbose: bool = False,
):
"""
Command to run Triton Inference Server inside container
Args:
framework: Framework used for model
repository_path: Path to model repository
strict_mode: Flag to use strict model config
poll_model: Poll model
metrics: Enable GPU metrics (disable for MIG)
verbose: Use verbose mode logging
Returns:
"""
triton_command = f"tritonserver --model-store={repository_path}"
if poll_model:
triton_command += " --model-control-mode=poll --repository-poll-secs 5"
else:
triton_command += " --model-control-mode=explicit"
if not strict_mode:
triton_command += " --strict-model-config=false"
if not metrics:
triton_command += " --allow-metrics=false --allow-gpu-metrics=false"
if verbose:
triton_command += " --log-verbose 1"
if framework in (Framework.TensorFlow1, Framework.TensorFlow2):
version = 1 if framework == Framework.TensorFlow1 else 2
triton_command += f" --backend-config=tensorflow,version={version}"
return triton_command
@staticmethod
def library_path(framework: str):
"""
Obtain custom library path for framework
Args:
framework: Framework used for model
Returns:
Path to additional libraries needed by framework
"""
paths = {
Framework.PyTorch.name: "/opt/tritonserver/backends/pytorch",
Framework.TensorFlow1.name: "/opt/tritonserver/backends/tensorflow1",
Framework.TensorFlow2.name: "/opt/tritonserver/backends/tensorflow2",
}
return paths[framework]
@staticmethod
def custom_library_path_remote() -> str:
"""
Path to custom library mounted in Triton container
Returns:
Path to shared library with custom operations
"""
return f"{Paths.LIBRARIES_PATH}/libcustomops.so"
@staticmethod
def custom_library_path_local(libs_dir: pathlib.Path) -> pathlib.Path:
"""
Path to custom library in local path
Args:
libs_dir: path to libraries directory
Returns:
Path to shared library with custom operations
"""
return libs_dir / "libcustomops.so"
|
TensorFlow/Classification/ConvNets/resnext101-32x4d | resnext101-32x4d | inference_benchmark | #!/bin/bash
DATA_DIR=${1:-"/data/tfrecords"}
DALI_DIR=${2}
BATCH_SIZE_TO_TEST="1 2 4 8 16 32 64 128"
INFERENCE_BENCHMARK=$(mktemp /tmp/inference-benchmark.XXXXXX)
function test_configuration() {
echo "Testing configuration: $1" | tee -a $INFERENCE_BENCHMARK
for BATCH in $BATCH_SIZE_TO_TEST; do
python ./main.py --arch=resnext101-32x4d --mode=inference_benchmark --warmup_steps 50 --num_iter 400 --iter_unit batch \
--batch_size $BATCH --data_dir=$DATA_DIR --results_dir=/tmp/results $2 | tail -n2 | head -n1 | sed \
's/^DLL \([0-9]*-\)*[0-9]* \([0-9]*:\)*[0-9]*.[0-9]* - ()/Results for BS='$BATCH'/' | tee -a $INFERENCE_BENCHMARK
if [ ! $? -eq 0 ]; then
echo "Failed test on batch size $BATCH_SIZE"
exit 1
fi
done
}
test_configuration "FP32 nodali noxla"
test_configuration "FP32 nodali xla" "--xla"
test_configuration "FP16 nodali noxla" "--amp"
test_configuration "FP16 nodali xla" "--amp --xla"
if [ ! -z $DALI_DIR ]; then
test_configuration "FP16 dali xla" "--amp --xla --dali --data_idx_dir ${DALI_DIR}"
fi
cat $INFERENCE_BENCHMARK
rm $INFERENCE_BENCHMARK
|
PyTorch/Segmentation/nnUNet/triton/deployment_toolkit/bermuda | bermuda | __init__ | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License. |
PyTorch/SpeechSynthesis/Tacotron2/filelists | filelists | ljs_audio_text_train_subset_2500_filelist | LJSpeech-1.1/wavs/LJ026-0104.wav|so starch manufactured in the leaves must be digested (dissolved) before it can be transported.
LJSpeech-1.1/wavs/LJ012-0101.wav|They had had serious work to get at the diamonds. It was necessary to force one heavy door from its hinges, and to cut through the thick panels of another.
LJSpeech-1.1/wavs/LJ012-0130.wav|brought in a man-of-war from Brazil had been transhipped at Falmouth for conveyance to London.
LJSpeech-1.1/wavs/LJ034-0049.wav|so no conclusions can be drawn as to whether these remaining prints preceded or followed the print developed in Dallas by powder.
LJSpeech-1.1/wavs/LJ011-0271.wav|Mr. Gee went in the coach sent for him, and alighted at twenty-seven, York Street, West, Commercial Road.
LJSpeech-1.1/wavs/LJ016-0393.wav|called for a roast duck directly he entered the condemned cell.
LJSpeech-1.1/wavs/LJ009-0256.wav|Still he resisted.
LJSpeech-1.1/wavs/LJ032-0195.wav|The Commission was able to conclude, however, that the fibers most probably came from Oswald's shirt.
LJSpeech-1.1/wavs/LJ032-0016.wav|and (eight) Oswald's capability with a rifle.
LJSpeech-1.1/wavs/LJ043-0053.wav|and became quite incensed with his wife when she would open the door for her in spite of his instructions to the contrary.
LJSpeech-1.1/wavs/LJ008-0162.wav|Cries of Murder! murder! were now raised, and added greatly to the horrors of the scene.
LJSpeech-1.1/wavs/LJ027-0026.wav|lead to a preview of certain principles of adaptation, necessary for their interpretation.
LJSpeech-1.1/wavs/LJ037-0073.wav|Addressing itself solely to the probative value of Mrs. Markham's contemporaneous description of the gunman
LJSpeech-1.1/wavs/LJ048-0182.wav|President Kennedy himself had mentioned it that morning, as had Agent Sorrels when he and Agent Lawson were fixing the motorcade route.
LJSpeech-1.1/wavs/LJ048-0199.wav|and arrest any person who might attempt to throw anything or try to get at the President and his party;
LJSpeech-1.1/wavs/LJ040-0104.wav|when he was sent to New Orleans to visit the family of his mother's sister, Mrs. Lillian Murret, for two or three weeks.
LJSpeech-1.1/wavs/LJ018-0312.wav|A plot was soon discovered,
LJSpeech-1.1/wavs/LJ016-0193.wav|Foxen asked him his name and address, and went away.
LJSpeech-1.1/wavs/LJ014-0330.wav|He had several narrow escapes.
LJSpeech-1.1/wavs/LJ028-0309.wav|After the twenty days are over, bid thy whole army attack the city on every side, and put me two bodies of Persians,
LJSpeech-1.1/wavs/LJ018-0321.wav|An increase of policemen on duty sufficed to prevent any attempt of this kind.
LJSpeech-1.1/wavs/LJ030-0039.wav|Men the motorcade slows or stops, agents take positions between the President and the crowd.
LJSpeech-1.1/wavs/LJ009-0290.wav|He was at first engaged as assistant to the executioner Tom Cheshire, but in due course rose to be chief.
LJSpeech-1.1/wavs/LJ038-0301.wav|(two) the photographs found among Oswald's possessions,
LJSpeech-1.1/wavs/LJ022-0028.wav|I am reminded sometimes of what President Wilson once said:
LJSpeech-1.1/wavs/LJ006-0214.wav|but no steps were taken to prevent any prisoner from obtaining more if he could pay for it.
LJSpeech-1.1/wavs/LJ047-0209.wav|that he had owned a weapon and did a good deal of hunting or use of it, perhaps in Russia, plus a number of items about his disposition and unreliability of character,
LJSpeech-1.1/wavs/LJ046-0140.wav|any communication, quote, that in any way indicates anyone may have possible intention of harming the President, end quote.
LJSpeech-1.1/wavs/LJ016-0415.wav|but the story was never substantiated, and we may hope that it rested only on the idle gossip of the day.
LJSpeech-1.1/wavs/LJ048-0106.wav|Much of Lawson's time was taken with establishing adequate security over the motorcade route and at the two places where the President would stop,
LJSpeech-1.1/wavs/LJ045-0030.wav|when his wife asked Oswald not to come to Irving.
LJSpeech-1.1/wavs/LJ001-0067.wav|In the Low Countries and Cologne, which were very fertile of printed books, Gothic was the favorite.
LJSpeech-1.1/wavs/LJ003-0320.wav|which recommended restrictions upon the number of visitors admitted.
LJSpeech-1.1/wavs/LJ018-0340.wav|characterized this as a crime more black and hideous than any in the criminal annals of the country.
LJSpeech-1.1/wavs/LJ045-0114.wav|Oswald also said that he did not want the FBI to know where he lived, quote, Because their visits were not very pleasant for him
LJSpeech-1.1/wavs/LJ038-0092.wav|Oswald provided little information during his questioning.
LJSpeech-1.1/wavs/LJ030-0047.wav|The occupants scanned the crowd and the buildings along the route.
LJSpeech-1.1/wavs/LJ033-0024.wav|Oswald replied, quote, I'm going home to get some curtain rods to put in an apartment, end quote.
LJSpeech-1.1/wavs/LJ010-0081.wav|One of the conspirators, by name Edwards,
LJSpeech-1.1/wavs/LJ028-0406.wav|The great irrigating dams across the Euphrates are constructed entirely of them.
LJSpeech-1.1/wavs/LJ048-0230.wav|and by a Secret Service investigation.
LJSpeech-1.1/wavs/LJ039-0053.wav|was of no probative value in the Commission's decision concerning the identity of the assassin of President Kennedy.
LJSpeech-1.1/wavs/LJ034-0039.wav|In Latona's opinion, quote,
LJSpeech-1.1/wavs/LJ039-0013.wav|and to the Commission on February twenty-one.
LJSpeech-1.1/wavs/LJ027-0160.wav|that the embryo or larva of a frog or toad, when first hatched, is a legless, tail-swimming, water-breathing, gill-breathing animal.
LJSpeech-1.1/wavs/LJ014-0283.wav|The jury found him guilty of the latter only, with a point of law reserved. This was fully argued before three judges,
LJSpeech-1.1/wavs/LJ014-0166.wav|faded in my mind before the atrocious bearing, looks, and language of the assembled spectators.
LJSpeech-1.1/wavs/LJ013-0093.wav|where the cash was transferred from the carpet-bag to a portmanteau.
LJSpeech-1.1/wavs/LJ005-0208.wav|the only aperture through which air could be admitted being an iron grating level with the street,
LJSpeech-1.1/wavs/LJ028-0303.wav|I think they will believe my words and entrust me with a command of troops. Thou, on thy part, must wait
LJSpeech-1.1/wavs/LJ030-0146.wav|Just prior to the shooting, David F. Powers, riding in the Secret Service follow-up car, remarked to Kenneth O'Donnell
LJSpeech-1.1/wavs/LJ003-0305.wav|The provision of more baths was also suggested, and the daily sweeping out of the prison.
LJSpeech-1.1/wavs/LJ017-0068.wav|and public opinion at the termination of the trial coincided with the verdict of the jury.
LJSpeech-1.1/wavs/LJ014-0136.wav|the culprit was really her husband, who killed O'Connor out of jealousy and revengeful feelings.
LJSpeech-1.1/wavs/LJ041-0042.wav|He wrote a note in his mother's name to school authorities in New Orleans saying that he was leaving school because he and his mother were moving to San Diego.
LJSpeech-1.1/wavs/LJ012-0053.wav|He was conveyed in a coach driven by a confederate, and under the escort of a couple of turnkeys.
LJSpeech-1.1/wavs/LJ048-0094.wav|Lawson was responsible for working out a great many arrangements for the President's trip.
LJSpeech-1.1/wavs/LJ033-0197.wav|quote, in all observable microscopic characteristics, end quote.
LJSpeech-1.1/wavs/LJ015-0142.wav|He soon proved his ability, and by unremitting attention mastered the whole work of the office.
LJSpeech-1.1/wavs/LJ012-0152.wav|which he refused to redeem on account of the row about the robbery.
LJSpeech-1.1/wavs/LJ018-0208.wav|were a low lot, the lowest among criminals except, perhaps, the 'smashers,' or those who passed the counterfeit money.
LJSpeech-1.1/wavs/LJ020-0017.wav|Now whip up the batter with a wooden spoon for another minute, and the sponge is made.
LJSpeech-1.1/wavs/LJ021-0081.wav|with the confidence that we are definitely rebuilding our political and economic system on the lines laid down by the New Deal
LJSpeech-1.1/wavs/LJ005-0288.wav|when speaking more particularly of the borough jails.
LJSpeech-1.1/wavs/LJ045-0172.wav|Answer: He said he would buy me a washing machine.
LJSpeech-1.1/wavs/LJ032-0009.wav|(two) the means by which the weapon was brought into the Depository Building,
LJSpeech-1.1/wavs/LJ044-0148.wav|very unhappy, and that he actually wept when he told her that.
LJSpeech-1.1/wavs/LJ015-0279.wav|One stroke of luck which he turned to great account
LJSpeech-1.1/wavs/LJ034-0080.wav|When he reached the first floor, the west elevator -- the one with the gate was not there.
LJSpeech-1.1/wavs/LJ004-0089.wav|and to pay overseers or instructors out of the county rates.
LJSpeech-1.1/wavs/LJ044-0040.wav|He wrote that, quote, thousands of circulars were distributed, end quote.
LJSpeech-1.1/wavs/LJ045-0213.wav|The conversation on Monday, November eighteen, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ029-0183.wav|On October three the Dallas Morning News quoted U.S. Representative Joe Pool's hope
LJSpeech-1.1/wavs/LJ014-0023.wav|and many of the same sort were found in the possession of the accused. This was enough to obtain a committal,
LJSpeech-1.1/wavs/LJ011-0291.wav|Two Bow Street runners were dispatched to the house in York Street, which had evidently been taken on purpose for the outrage.
LJSpeech-1.1/wavs/LJ045-0151.wav|He then arrived on Thursday, November twenty-one, nineteen sixty-three, end quote.
LJSpeech-1.1/wavs/LJ027-0088.wav|Extensive comparison, on the contrary, shows them to be the same, although the essential identity is obscured by adaptive modifications.
LJSpeech-1.1/wavs/LJ028-0352.wav|whether of former or of later times, except only Cyrus with whom no person ever yet thought himself worthy to compare.
LJSpeech-1.1/wavs/LJ031-0152.wav|Agents Kellerman and Hill telephoned the head of the White House detail, Gerald A. Behn, to advise him of the assassination.
LJSpeech-1.1/wavs/LJ025-0084.wav|And if we substitute for the possession of an alimentary cavity the power of taking solid nutriment into the body and there digesting it,
LJSpeech-1.1/wavs/LJ025-0149.wav|that, while locomotive, their movements may have as much appearance of spontaneity as those of the lowest animals,
LJSpeech-1.1/wavs/LJ050-0158.wav|the Department hopes to design a practical system which will fully meet the needs of the Protective Research Section of the Secret Service.
LJSpeech-1.1/wavs/LJ030-0123.wav|Special Agent Glen A. Bennett once left his place inside the follow-up car to help keep the crowd away from the President's car.
LJSpeech-1.1/wavs/LJ022-0089.wav|charged with carrying on work relief projects.
LJSpeech-1.1/wavs/LJ030-0008.wav|During the afternoon, President Kennedy dedicated the U.S. Air Force School of Aerospace Medicine at Brooks Air Force Base.
LJSpeech-1.1/wavs/LJ007-0059.wav|had relaxed his efforts, because, according to his own account, he was so frequently stopped in the performance of his duties.
LJSpeech-1.1/wavs/LJ037-0258.wav|There is no doubt, however, that Oswald was seen leaving his roominghouse at about one p.m. wearing a zipper jacket,
LJSpeech-1.1/wavs/LJ039-0062.wav|the shots were at a slow-moving target proceeding on a downgrade in virtually a straight line
LJSpeech-1.1/wavs/LJ032-0199.wav|the Oswalds lived on Neely Street in Dallas in a rented house which had a small back yard.
LJSpeech-1.1/wavs/LJ014-0244.wav|which offered peculiar chances of profit to an ingenious and unscrupulous man.
LJSpeech-1.1/wavs/LJ040-0128.wav|He was in Youth House from April sixteen to May seven, nineteen fifty-three,
LJSpeech-1.1/wavs/LJ042-0062.wav|It shows how willing he was to act dramatically and decisively when he faced an emotional crisis
LJSpeech-1.1/wavs/LJ050-0007.wav|have made it difficult for the Treasury to maintain close and continuing supervision.
LJSpeech-1.1/wavs/LJ028-0021.wav|Again, long before the stars have been scattered by the morning sun, you are on your way.
LJSpeech-1.1/wavs/LJ030-0033.wav|Vice President and Mrs. Johnson followed along the fence, guarded by four members of the Vice-Presidential detail.
LJSpeech-1.1/wavs/LJ033-0123.wav|that the bag she saw Oswald carrying, quote, wasn't that long, I mean it was folded down at the top as I told you. It definitely wasn't that long, end quote,
LJSpeech-1.1/wavs/LJ009-0130.wav|winked at other prisoners in derision of what was taking place; and I have frequently heard men and lads who had been of the kneeling party
LJSpeech-1.1/wavs/LJ035-0201.wav|The fact that Truly found Fritz in the northwest corner of the floor, near the point where the rifle was found, supports Fritz' recollection.
LJSpeech-1.1/wavs/LJ031-0113.wav|This operation was concluded at three:twenty p.m.
LJSpeech-1.1/wavs/LJ014-0025.wav|A witness deposed to meeting Hocker, soon after the cries of murder were heard,
LJSpeech-1.1/wavs/LJ014-0007.wav|He entered into conversation with the policemen, and learnt, as it seemed for the first time, what had happened.
LJSpeech-1.1/wavs/LJ009-0110.wav|This exhibition lasts for some minutes, and then the congregation disperses,
LJSpeech-1.1/wavs/LJ035-0090.wav|possible delayed reaction to the shot, jostling with the crowd of people on the steps and scanning the area along Elm Street and the parkway.
LJSpeech-1.1/wavs/LJ028-0449.wav|Parts of the walls of Nineveh are still standing to the height of one hundred and twenty-five feet,
LJSpeech-1.1/wavs/LJ050-0210.wav|the caseload of each FBI agent averaged twenty to twenty-five, and he felt that this was high.
LJSpeech-1.1/wavs/LJ021-0119.wav|including a few of major importance.
LJSpeech-1.1/wavs/LJ003-0279.wav|There was fear as to the unrestricted use of tools,
LJSpeech-1.1/wavs/LJ031-0184.wav|Swearing in of the New President
LJSpeech-1.1/wavs/LJ027-0030.wav|is associated with an adaptive modification of locomotor structures, legs and wings,
LJSpeech-1.1/wavs/LJ006-0155.wav|He may have erred in some points through ignorance, but in others he was clearly guilty of culpable neglect.
LJSpeech-1.1/wavs/LJ025-0053.wav|to the investigation of organic structure,
LJSpeech-1.1/wavs/LJ047-0027.wav|In this way, it learned that when Oswald had arrived in the Soviet Union
LJSpeech-1.1/wavs/LJ033-0046.wav|went out to the garage to paint some children's blocks, and worked in the garage for half an hour or so.
LJSpeech-1.1/wavs/LJ037-0038.wav|at the southeast corner of the intersection, approximately fifty feet away.
LJSpeech-1.1/wavs/LJ003-0117.wav|A bribe to the judge was certain to secure acquittal, and the neglect of the formality was as certainly followed by condemnation.
LJSpeech-1.1/wavs/LJ030-0208.wav|Hill heard a noise, which seemed to be a firecracker, coming from his right rear.
LJSpeech-1.1/wavs/LJ010-0041.wav|or like Cannon the chimney-sweeper, who savagely killed the policeman.
LJSpeech-1.1/wavs/LJ002-0122.wav|The number of arrests actually made was one hundred fourteen thousand, three hundred for the kingdom, and seven thousand twenty for Middlesex.
LJSpeech-1.1/wavs/LJ032-0080.wav|were a Selective Service notice of classification and a Marine certificate of service in the name of Alek James Hidell.
LJSpeech-1.1/wavs/LJ036-0101.wav|He was taken to the lineup room where, according to Whaley, five young teenagers, all handcuffed together, were displayed with Oswald.
LJSpeech-1.1/wavs/LJ044-0233.wav|Oswald was carrying only thirteen dollars, eighty-seven cents at the time of his arrest, although he had left, apparently by design,
LJSpeech-1.1/wavs/LJ015-0134.wav|had assets in the shape of land, house, furniture, pictures, and objets d'art to the value of fifty thousand pounds.
LJSpeech-1.1/wavs/LJ021-0067.wav|a rise from a deficit figure in the first quarter of nineteen thirty-three
LJSpeech-1.1/wavs/LJ001-0121.wav|in reading the modern figures the eyes must be strained before the reader can have any reasonable assurance
LJSpeech-1.1/wavs/LJ038-0304.wav|on April ten, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ014-0089.wav|For the remainder of that week and part of the next the murderers stayed in the house, and occupied the kitchen, close to the remains of their victim.
LJSpeech-1.1/wavs/LJ008-0209.wav|Soon after midnight on the Sunday night, for by this time the present practice of executing on Monday morning had been pretty generally introduced,
LJSpeech-1.1/wavs/LJ028-0336.wav|Darius now, still keeping to the plan agreed upon,
LJSpeech-1.1/wavs/LJ031-0102.wav|Governor Connally was originally seen by Dr. Carrico and Dr. Richard Dulany.
LJSpeech-1.1/wavs/LJ009-0133.wav|the outside public continued to be excluded from the Newgate chapel on the day the condemned sermon was preached.
LJSpeech-1.1/wavs/LJ006-0177.wav|and it was not the least part of the blame imputed to him that he made special favorites of particular prisoners, retaining of his own accord in Newgate,
LJSpeech-1.1/wavs/LJ049-0098.wav|In nineteen oh two bills passed both Houses of Congress but failed of enactment when the Senate refused to accept the conference report.
LJSpeech-1.1/wavs/LJ014-0176.wav|His determined addiction to evil courses had led to his being cast off by his family,
LJSpeech-1.1/wavs/LJ009-0301.wav|who deserted, and was pursued, but without success.
LJSpeech-1.1/wavs/LJ047-0013.wav|Finally, the Commission has reviewed the complete files on Oswald, as they existed at the time of the assassination, of the Department of State,
LJSpeech-1.1/wavs/LJ037-0157.wav|taken from Oswald.
LJSpeech-1.1/wavs/LJ041-0087.wav|as a means of getting or attempting to get sympathy, end quote. In Thornley's view, Oswald labored under a persecution complex
LJSpeech-1.1/wavs/LJ003-0090.wav|Mr. Newman admitted that he had petitioned that certain "trusty men" might be left in the jail.
LJSpeech-1.1/wavs/LJ040-0015.wav|There is, however, a large amount of material available in his writings
LJSpeech-1.1/wavs/LJ007-0068.wav|generally sided with his opponents. Nevertheless the inspectors summed up against him.
LJSpeech-1.1/wavs/LJ029-0148.wav|for controlling the crowds and traffic, watching the overpasses, and providing motorcycle escort.
LJSpeech-1.1/wavs/LJ035-0205.wav|and no one could be found who saw Oswald anywhere else in the building until after the shooting.
LJSpeech-1.1/wavs/LJ017-0269.wav|let down. A full view of them was thus at all times obtainable by the officers who, without intermission, day and night patrolled the ward.
LJSpeech-1.1/wavs/LJ010-0304.wav|through advances made to various builders, and that it could only maintain its credit by wholesale discounting.
LJSpeech-1.1/wavs/LJ025-0138.wav|The results of inquiries into the structure of the nervous system of animals
LJSpeech-1.1/wavs/LJ005-0262.wav|it was suggested that the rules framed for prison government should be subjected to the Secretary of State for approval,
LJSpeech-1.1/wavs/LJ020-0105.wav|Weave the little duties in and under and among what seem to be the greater.
LJSpeech-1.1/wavs/LJ010-0313.wav|the sum total amounting to some one hundred seventy thousand pounds, with a declaration in his own handwriting to the following effect.
LJSpeech-1.1/wavs/LJ014-0169.wav|It will be in the memory of many that Mrs. Manning appeared on the scaffold in a black satin dress, which was bound tightly round her waist.
LJSpeech-1.1/wavs/LJ020-0001.wav|Marion Harland's Cookery for Beginners. Bread Sponge and Breakfast Breads.
LJSpeech-1.1/wavs/LJ048-0047.wav|his presence in the School Book Depository job and its location along the route of the motorcade.
LJSpeech-1.1/wavs/LJ050-0145.wav|and the Commission recommends that these and the other measures suggested by the Commission be pursued vigorously by Secret Service.
LJSpeech-1.1/wavs/LJ010-0151.wav|Again, a soldier, by name Hatfield, who had been wounded in the head, and discharged from the army for unsoundness of mind,
LJSpeech-1.1/wavs/LJ016-0253.wav|that the ceremony may be made more mechanical, thus rendering the personal intervention of a skilled functionary unnecessary.
LJSpeech-1.1/wavs/LJ036-0078.wav|claimed that about fifteen minutes after the assassination he saw a man, whom he later identified as Oswald,
LJSpeech-1.1/wavs/LJ014-0066.wav|and by dint of usurious interest on small sums advanced to needy neighbors, had amassed as much as eight thousand pounds or ten thousand pounds.
LJSpeech-1.1/wavs/LJ040-0126.wav|Oswald was remanded for psychiatric observation to Youth House, an institution in which children are kept for psychiatric observation
LJSpeech-1.1/wavs/LJ009-0152.wav|The crowd outside Newgate on the day of execution has already been described; but there was also a select gathering of distinguished visitors within the jail.
LJSpeech-1.1/wavs/LJ007-0179.wav|defeats the ends of justice, and disgraces the profession of a Christian country.
LJSpeech-1.1/wavs/LJ028-0140.wav|The city stands on a broad plain, and is an exact square, a hundred and twenty furlongs in length each way,
LJSpeech-1.1/wavs/LJ033-0044.wav|In the garage were the personal belongings of the Oswald family including, as the evidence has shown, the rifle wrapped in the old brown and green blanket.
LJSpeech-1.1/wavs/LJ028-0472.wav|Its outer part, about twelve feet in width, was protected with towers at intervals of sixty-five feet.
LJSpeech-1.1/wavs/LJ044-0016.wav|which was berthed at the Dumaine Street wharf in New Orleans, on June sixteen, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ031-0030.wav|Governor Connally, who had lost consciousness on the ride to the hospital, regained consciousness when the limousine stopped abruptly at the emergency entrance.
LJSpeech-1.1/wavs/LJ029-0011.wav|President Kennedy's visit to Texas in November nineteen sixty-three had been under consideration for almost a year before it occurred.
LJSpeech-1.1/wavs/LJ034-0157.wav|Brennan stated, quote, I could at that time -- I could, with all sincerity, identify him as being the same man, end quote.
LJSpeech-1.1/wavs/LJ023-0110.wav|a super-legislature, as one of the justices has called it
LJSpeech-1.1/wavs/LJ028-0231.wav|whereupon they withdrew within their defenses.
LJSpeech-1.1/wavs/LJ016-0163.wav|He might have saved himself at any moment by merely extending an arm; but he lay there patiently till death supervened.
LJSpeech-1.1/wavs/LJ003-0336.wav|but it at once deprecated the idea that the city could follow the laudable example thus set in the provinces. Quote,
LJSpeech-1.1/wavs/LJ016-0147.wav|Then he ran along the coping of the wall towards its angle with Tyler's manufactory, and dropped down on to the gridiron below.
LJSpeech-1.1/wavs/LJ036-0086.wav|The Commission could not accept important elements of Craig's testimony.
LJSpeech-1.1/wavs/LJ030-0241.wav|President Johnson emphasized Youngblood's instantaneous reaction after the first shot:
LJSpeech-1.1/wavs/LJ004-0058.wav|The untried, and in the eyes of the law still innocent, could claim pure air, wholesome and sufficient food, and opportunities for exercise.
LJSpeech-1.1/wavs/LJ003-0041.wav|There was no lack of air and light for the new jail, and several exercising yards.
LJSpeech-1.1/wavs/LJ048-0027.wav|Nowhere during the course of this investigation or the information that came to us from other agencies was there any indication of a potential for violence on his part.
LJSpeech-1.1/wavs/LJ048-0045.wav|his pro-Castro tendencies, his lies when interrogated by the FBI,
LJSpeech-1.1/wavs/LJ003-0217.wav|The condemned occupied an open pew in the center of the chapel, hung with black; in front of them, upon a table, was a black coffin in full view.
LJSpeech-1.1/wavs/LJ011-0061.wav|Let this monster give his name; I am ready to fight him. I am still determined to put myself in the place of Mr. Fauntleroy.
LJSpeech-1.1/wavs/LJ037-0127.wav|Four men -- Warren Reynolds, Harold Russell, Pat Patterson, and L. J. Lewis
LJSpeech-1.1/wavs/LJ029-0208.wav|It was fashioned after the "wanted" circulars issued by law enforcement agencies.
LJSpeech-1.1/wavs/LJ003-0236.wav|Garnish continued to be demanded long after it had disappeared in other and better-regulated prisons.
LJSpeech-1.1/wavs/LJ041-0036.wav|He was a little dismayed at this, and he said that he couldn't find any that would show any interest in him as a Communist,
LJSpeech-1.1/wavs/LJ007-0155.wav|to be subjected to the same baneful influences, and to suffer the same moral deterioration, whether ultimately convicted or set free.
LJSpeech-1.1/wavs/LJ028-0070.wav|and how, in punishment for all his wickedness, he became a calf, and for seven years grazed the grass in the fields about the city.
LJSpeech-1.1/wavs/LJ021-0136.wav|We have passed through more than a year of education.
LJSpeech-1.1/wavs/LJ013-0250.wav|In the same room a large axe and saw were found covered with blood.
LJSpeech-1.1/wavs/LJ002-0263.wav|the Lord Steward of the Household, the steward and officers of the Marshalsea Court, and others.
LJSpeech-1.1/wavs/LJ032-0162.wav|Stombaugh testified that the colors, shades, and twist of the fibers found in the tuft on the rifle matched those in Oswald's shirt.
LJSpeech-1.1/wavs/LJ038-0279.wav|I think is going overboard in the other direction.
LJSpeech-1.1/wavs/LJ048-0023.wav|and he had told us during one of the interviews that he would probably take his wife back to Soviet Russia some time in the future.
LJSpeech-1.1/wavs/LJ038-0118.wav|The Aliases "Hidell" and "O. H. Lee"
LJSpeech-1.1/wavs/LJ015-0139.wav|an open-handed, unthinking charity which gave freely to the poor and needy the money which belonged to his creditors.
LJSpeech-1.1/wavs/LJ015-0037.wav|and the partners had to decide between suspending payment or continuing to hold its head above water by flagitious processes.
LJSpeech-1.1/wavs/LJ025-0090.wav|and resemblances between the constituents of animal and vegetable organisms, for which Cuvier is not responsible,
LJSpeech-1.1/wavs/LJ012-0078.wav|One of the largest robberies of its class was that effected upon the Custom House in the winter of eighteen thirty-four.
LJSpeech-1.1/wavs/LJ021-0208.wav|into the service of the privileged few.
LJSpeech-1.1/wavs/LJ028-0245.wav|and mounting upon the walls along both sides of the stream, would so have caught the enemy as it were in a trap.
LJSpeech-1.1/wavs/LJ022-0010.wav|At different points on the coast where I often visit they build great seagoing ships.
LJSpeech-1.1/wavs/LJ017-0217.wav|Navigation and discipline could not be easy with such a nondescript crew.
LJSpeech-1.1/wavs/LJ010-0126.wav|A crowd as great as any known collected in the Old Bailey to see the ceremony, about which there were some peculiar features worth recording.
LJSpeech-1.1/wavs/LJ035-0046.wav|I was coming out this one on the second floor, and I don't know, I was kind of sweeping this area as I come up, I was looking from right to left
LJSpeech-1.1/wavs/LJ037-0166.wav|He concluded, however, that he could not say whether the four bullets were fired from the revolver in Oswald's possession.
LJSpeech-1.1/wavs/LJ045-0176.wav|The next morning he left for work before anyone else arose.
LJSpeech-1.1/wavs/LJ012-0264.wav|a warrant was issued for his apprehension, which was effected at Kennington on the twenty-fourth March.
LJSpeech-1.1/wavs/LJ014-0088.wav|This was on a Thursday evening.
LJSpeech-1.1/wavs/LJ032-0017.wav|Ownership And Possession Of Assassination Weapon
LJSpeech-1.1/wavs/LJ034-0093.wav|Brennan also testified that Lee Harvey Oswald,
LJSpeech-1.1/wavs/LJ045-0137.wav|I and my wife strongly protested these tactics by the notorious F.B.I., end quote.
LJSpeech-1.1/wavs/LJ004-0119.wav|which had continued through that long period, are forcibly pointed out.
LJSpeech-1.1/wavs/LJ005-0067.wav|The Prison Society reproves the misdirected efforts of ambitious architects, who by a lavish and improvident expenditure of public money
LJSpeech-1.1/wavs/LJ016-0080.wav|and probably one of the few cases of a recurrence, but under proper safeguards and limitations, to the old system of chains.
LJSpeech-1.1/wavs/LJ002-0078.wav|seven. The press yard was that part set aside for the condemned.
LJSpeech-1.1/wavs/LJ030-0043.wav|Its function was to alert police along the route that the motorcade was approaching and to check for signs of trouble.
LJSpeech-1.1/wavs/LJ003-0148.wav|and spent in providing coals, candles, plates, knives, and forks; while all the occupants of this part of the prison
LJSpeech-1.1/wavs/LJ033-0051.wav|Neither Marina Oswald nor Ruth Paine saw Oswald in the garage.
LJSpeech-1.1/wavs/LJ010-0176.wav|He was on the right or north side of the road. Prince Albert occupied the same side of the carriage, the Queen the left.
LJSpeech-1.1/wavs/LJ043-0153.wav|When asked if Oswald requested the note back she testified that, quote, He forgot about it. But apparently
LJSpeech-1.1/wavs/LJ018-0160.wav|They next watched Buncher, and found that he paid frequent visits to Birmingham.
LJSpeech-1.1/wavs/LJ018-0229.wav|The day his father died he got the keys of his private bureau, opened it, and took out the authentic will.
LJSpeech-1.1/wavs/LJ031-0204.wav|with three Secret Service agents, accompanied President Kennedy's body on the forty-five-minute automobile trip from Andrews Air Force Base to the hospital.
LJSpeech-1.1/wavs/LJ029-0184.wav|that President Kennedy would receive a "good welcome" and would not face demonstrations like those encountered
LJSpeech-1.1/wavs/LJ049-0229.wav|while assuming no radical relocation of responsibilities,
LJSpeech-1.1/wavs/LJ029-0136.wav|through the underpass and leads into an access road,
LJSpeech-1.1/wavs/LJ003-0228.wav|and the general insufficiency was such
LJSpeech-1.1/wavs/LJ033-0166.wav|Among other tests, the paper and tape were submitted to fiber analysis and spectrographic examination.
LJSpeech-1.1/wavs/LJ049-0033.wav|to move into the passenger section without hindrance or delay. Had the vehicle been so designed it is possible that an agent riding in the front seat
LJSpeech-1.1/wavs/LJ042-0121.wav|Mass gymnastics, compulsory afterwork meeting, usually political information meeting.
LJSpeech-1.1/wavs/LJ018-0344.wav|In cold-blooded premeditation it rivaled that of the Mannings.
LJSpeech-1.1/wavs/LJ003-0029.wav|Under the steward there were captains of wards, chosen in the same way, and performing analogous duties.
LJSpeech-1.1/wavs/LJ020-0099.wav|When habited for the day in all except the outer gown, collar, etc., slip on the wrapper again and run down to put the biscuits in the oven.
LJSpeech-1.1/wavs/LJ018-0214.wav|As the case must still be well remembered by the present generation, it will be necessary to give here only the briefest summary.
LJSpeech-1.1/wavs/LJ015-0130.wav|fifteen hundred pounds, which larger amount was duly carried to his credit on the register, and entered upon the certificates of transfer.
LJSpeech-1.1/wavs/LJ010-0105.wav|Thistlewood was discovered next morning in a mean house in White Street, Moorfields.
LJSpeech-1.1/wavs/LJ041-0163.wav|out of a combination of Oswald's known Marxist sympathies and George Orwell's book "nineteen eighty-four," one of Oswald's favorite books
LJSpeech-1.1/wavs/LJ006-0305.wav|The house at this time was full of men and visitors; waiters came in from the taverns with meals.
LJSpeech-1.1/wavs/LJ006-0010.wav|Mr. Samuel Hoare, when examined, considered it indispensably necessary, to carry out whatever system might be established,
LJSpeech-1.1/wavs/LJ009-0053.wav|but who is left to die on the supposition that this is not his first conviction, and still more because a good many sheep have of late been stolen by other people.
LJSpeech-1.1/wavs/LJ017-0145.wav|Dr. Smethurst was long an inmate of Newgate, and was tried at the Central Criminal Court.
LJSpeech-1.1/wavs/LJ035-0119.wav|until after they saw Patrolman Baker's white helmet on the fifth floor moving toward the elevator.
LJSpeech-1.1/wavs/LJ017-0177.wav|Wilson was acquitted on this charge, but other suspicious facts cropped up while she was in Newgate.
LJSpeech-1.1/wavs/LJ045-0044.wav|Many of the people with whom the Oswalds became acquainted after their arrival in the United States thought that Marina Oswald had married her husband primarily in the hope
LJSpeech-1.1/wavs/LJ008-0108.wav|The ordinary "gravely uttered, 'Come this way, Mr. Smith.'
LJSpeech-1.1/wavs/LJ010-0241.wav|but she declared she would not remain a prisoner in her own palace, and next day drove out as usual in an open barouche.
LJSpeech-1.1/wavs/LJ050-0237.wav|the FBI, on sixteen separate occasions, supplied a total of one hundred thirty-nine agents to assist in protection work during a Presidential visit,
LJSpeech-1.1/wavs/LJ032-0203.wav|on November twenty-two, nineteen sixty-three. One of these pictures, Exhibit Number one thirty-three A, shows most of the rifle's configuration.
LJSpeech-1.1/wavs/LJ005-0116.wav|but an empty regulation which all so disposed could defy.
LJSpeech-1.1/wavs/LJ047-0041.wav|Agent Fain reported to headquarters that Oswald was impatient and arrogant,
LJSpeech-1.1/wavs/LJ012-0178.wav|Thurtell drove him down in a gig, "to be killed as he traveled," in Thurtell's own words.
LJSpeech-1.1/wavs/LJ047-0193.wav|and so advised the Dallas office in the ordinary course of business.
LJSpeech-1.1/wavs/LJ006-0130.wav|had a key of both the master's side and middle side yards, was the only person present at the distribution of beer, and was trusted to examine,
LJSpeech-1.1/wavs/LJ009-0179.wav|the most recent enactment in force was the ninth George the fourth cap. thirty-one, which directed the dissection of all bodies of executed murderers,
LJSpeech-1.1/wavs/LJ012-0046.wav|The second house was in Lower Queen Street, Islington, and he used it for some time as a depot for valuables.
LJSpeech-1.1/wavs/LJ028-0483.wav|O Marduk, great god, look joyfully upon the precious work of my hands. Be thou my protector.
LJSpeech-1.1/wavs/LJ041-0127.wav|Oswald must have already learned that the Governor could not help him with his discharge because he was no longer Secretary of the Navy, at the time he made that remark.
LJSpeech-1.1/wavs/LJ012-0074.wav|Whether Ikey was "assigned" to his own family is not recorded, but no doubt he succeeded to his own property when the term of servitude had expired.
LJSpeech-1.1/wavs/LJ009-0029.wav|This episode throws some doubt upon the tenderness and proper feeling exhibited by the chaplain towards the most deserving members of his criminal flock;
LJSpeech-1.1/wavs/LJ032-0176.wav|Moreover, the bus transfer which he obtained as he left the bus was still in the pocket when he was arrested.
LJSpeech-1.1/wavs/LJ037-0107.wav|They saw a man coming south on Patton with a revolver held high in his right hand. According to Callaway, the man crossed to the west side of Patton.
LJSpeech-1.1/wavs/LJ004-0127.wav|In one hundred jails,
LJSpeech-1.1/wavs/LJ006-0077.wav|The fact was, he did not keep the classification of prisoners on first arrival in his own hands, nor even in that of his officers.
LJSpeech-1.1/wavs/LJ009-0259.wav|The wretched man did not fall with it, but jumped on to the platform, and seizing the rope with his hands, tried to avoid strangulation.
LJSpeech-1.1/wavs/LJ035-0128.wav|If her estimate of time is correct, she reached the bottom of the stairs before Truly and Baker started up,
LJSpeech-1.1/wavs/LJ005-0138.wav|that in four prisons, which at one time of the year contained one thousand three hundred eight prisoners, there were only sixty-eight sleeping rooms or cells,
LJSpeech-1.1/wavs/LJ040-0108.wav|which became more significant as the children grew older.
LJSpeech-1.1/wavs/LJ010-0167.wav|He left his last situation in April eighteen forty, and established himself in lodgings in Lambeth,
LJSpeech-1.1/wavs/LJ036-0107.wav|because he was bawling out the policeman, telling them it wasn't right to put him in line with these teenagers and all of that
LJSpeech-1.1/wavs/LJ044-0128.wav|there are a number of organizations, including possibly Fair Play, which are of a very broad character,
LJSpeech-1.1/wavs/LJ017-0125.wav|He never actually said that he was not guilty, but he was confident he would not be convicted.
LJSpeech-1.1/wavs/LJ039-0041.wav|I am getting a little confused with so many questions.
LJSpeech-1.1/wavs/LJ003-0339.wav|could possibly afford.
LJSpeech-1.1/wavs/LJ003-0156.wav|All the money earned by prisoners was at their own disposal, and was spent almost habitually in drink, chambering, and wantonness.
LJSpeech-1.1/wavs/LJ035-0210.wav|On the basis of these findings the Commission has concluded that Oswald, at the time of the assassination,
LJSpeech-1.1/wavs/LJ010-0256.wav|Undeterred by the well-merited punishment which had overtaken Francis,
LJSpeech-1.1/wavs/LJ011-0013.wav|replaced the stock in the names of the original holders, who might otherwise have been completely ruined.
LJSpeech-1.1/wavs/LJ036-0148.wav|After a review of these inconsistencies in his testimony before the Commission, Whaley was interviewed again in Dallas.
LJSpeech-1.1/wavs/LJ019-0130.wav|since admirably developed in the convict prisons of this country.
LJSpeech-1.1/wavs/LJ028-0389.wav|St. Jerome said:
LJSpeech-1.1/wavs/LJ006-0195.wav|This was admitted in evidence by the turnkeys, and was proved by the appearance of the prison tables, which bore the marks of gaming-boards deeply cut into them.
LJSpeech-1.1/wavs/LJ048-0034.wav|no law enforcement agency had any information to connect Oswald with the attempted shooting of General Walker.
LJSpeech-1.1/wavs/LJ045-0243.wav|He does not appear to have been able to establish meaningful relationships with other people. He was perpetually discontented with the world around him.
LJSpeech-1.1/wavs/LJ016-0057.wav|As his coat was an encumbrance, he left it on the top of the third house in Newgate Street, and thus in shirt-sleeves, barefoot and bareheaded,
LJSpeech-1.1/wavs/LJ014-0061.wav|and Manning hoped to get some small Government appointment through his wife's interest.
LJSpeech-1.1/wavs/LJ013-0084.wav|Burgess fraudulently transferred consols to the above amount, standing in the name of Mr. Oxenford, to another party.
LJSpeech-1.1/wavs/LJ018-0126.wav|His object in visiting Whitchurch was to undermine the honesty of some workman in the mills;
LJSpeech-1.1/wavs/LJ038-0201.wav|James C. Cadigan, FBI handwriting expert, testified that this note was written by Lee Harvey Oswald.
LJSpeech-1.1/wavs/LJ019-0310.wav|which had long been admitted as indispensable, and had never as yet been properly obtained.
LJSpeech-1.1/wavs/LJ029-0182.wav|may not endorse him in 'sixty-four.
LJSpeech-1.1/wavs/LJ043-0066.wav|Some of his acquaintances, feeling that Oswald tried to impress people with the fact that he had lived and worked in Russia, were led to the belief
LJSpeech-1.1/wavs/LJ004-0132.wav|the old evils of indiscriminate association still continued unchecked.
LJSpeech-1.1/wavs/LJ042-0197.wav|seemed to place him in a situation in which he could not live with satisfaction either in the United States or in the Soviet Union.
LJSpeech-1.1/wavs/LJ018-0366.wav|Although sentence of death was passed on Edmunds, it was commuted to penal servitude for life;
LJSpeech-1.1/wavs/LJ010-0237.wav|A youth named Pearson had seen him present a pistol at the Queen's carriage,
LJSpeech-1.1/wavs/LJ049-0039.wav|to take a protective position in the passenger compartment before the third shot was fired.
LJSpeech-1.1/wavs/LJ049-0155.wav|while investigating a plot to assassinate President Cleveland, the Service assigned a small protective detail of agents to the White House.
LJSpeech-1.1/wavs/LJ008-0138.wav|and at his request the ordinary drew the cap further down over his face, when in an instant,
LJSpeech-1.1/wavs/LJ027-0139.wav|and developmental changes which may be observed during the life history of now existing individuals belonging to the same group of animals.
LJSpeech-1.1/wavs/LJ049-0010.wav|who responded to the unplanned event with dispatch.
LJSpeech-1.1/wavs/LJ005-0149.wav|The nature of the employment varied greatly in severity, especially the tread-wheel labor.
LJSpeech-1.1/wavs/LJ021-0041.wav|has been to clean up thoroughly unwholesome conditions in the field of investment.
LJSpeech-1.1/wavs/LJ032-0065.wav|In accordance with postal regulations, the portion of the application which lists names of persons, other than the applicant, entitled to receive mail
LJSpeech-1.1/wavs/LJ022-0020.wav|cause of clearer thinking and a better understanding, are considering the whole rather than a mere part relating to one section or to one crop,
LJSpeech-1.1/wavs/LJ035-0146.wav|saw him walk through the clerical office on the second floor toward the door leading to the front stairway.
LJSpeech-1.1/wavs/LJ018-0259.wav|he confessed that his whole life had been a gigantic mistake, and he was ready to make what atonement he could.
LJSpeech-1.1/wavs/LJ040-0113.wav|They moved shortly after Robert joined the Marines; they lived for a time with John Pic who was stationed there with the Coast Guard.
LJSpeech-1.1/wavs/LJ003-0239.wav|This imposition of fees left prisoners destitute on their discharge, without funds to support them in their first struggle to recommence life,
LJSpeech-1.1/wavs/LJ028-0011.wav|As the taps upon her shoulder are repeated, she stretches out her long neck, and with long strides makes for the eastern horizon;
LJSpeech-1.1/wavs/LJ041-0157.wav|He studied the Russian language, read a Russian language newspaper and seemed interested in what was going on in the Soviet Union.
LJSpeech-1.1/wavs/LJ015-0015.wav|A more distressing case stands next on the criminal records --
LJSpeech-1.1/wavs/LJ001-0048.wav|his letter is admirably clear and regular, but at least as beautiful as any other Roman type.
LJSpeech-1.1/wavs/LJ006-0034.wav|They attended early and late; they mustered the prisoners, examined into their condition,
LJSpeech-1.1/wavs/LJ004-0124.wav|In four hundred and forty-five prisons no work of any description had been introduced for the employment of prisoners;
LJSpeech-1.1/wavs/LJ032-0106.wav|end quote. Hidell was a fictitious president of an organization of which Oswald was the only member.
LJSpeech-1.1/wavs/LJ002-0026.wav|in the three years between eighteen thirteen and eighteen sixteen,
LJSpeech-1.1/wavs/LJ043-0126.wav|told the prospective employer that Oswald was, quote, kinda peculiar sometimes and that he had some knowledge of the Russian language, end quote.
LJSpeech-1.1/wavs/LJ019-0338.wav|But discipline was to be maintained if necessary by punishment,
LJSpeech-1.1/wavs/LJ037-0077.wav|Barbara Jeanette Davis and Virginia Davis, were in an apartment of a multiple-unit house on the southeast corner of tenth and Patton
LJSpeech-1.1/wavs/LJ034-0206.wav|confirmed that Euins could neither describe the man in the window nor indicate his race.
LJSpeech-1.1/wavs/LJ006-0178.wav|and for years, felons who should have been sent beyond the seas.
LJSpeech-1.1/wavs/LJ037-0112.wav|Apparently he had reached for his gun; it lay beneath him outside of the holster.
LJSpeech-1.1/wavs/LJ028-0396.wav|they were supplied with food by keepers, and gave the king the opportunity of hunting whenever he felt inclined.
LJSpeech-1.1/wavs/LJ047-0187.wav|It was then my plan to interview Marina Oswald in detail concerning both herself and her husband's background. Question:
LJSpeech-1.1/wavs/LJ037-0220.wav|Approximately fifteen minutes before the shooting of Tippit, Oswald was seen leaving his roominghouse.
LJSpeech-1.1/wavs/LJ040-0014.wav|He cannot, of course, be questioned or observed by those charged with the responsibility for this report or by experts on their behalf.
LJSpeech-1.1/wavs/LJ045-0185.wav|he asked Frazier for a ride to Irving that night, stating falsely that he wanted to pick up some curtain rods to put in an apartment.
LJSpeech-1.1/wavs/LJ011-0261.wav|He was found guilty of an assault with intent, and sentenced to transportation for fourteen years.
LJSpeech-1.1/wavs/LJ046-0107.wav|Finally, the performance of those charged with the immediate responsibility of protecting the President on November twenty-two is reviewed.
LJSpeech-1.1/wavs/LJ023-0073.wav|The Court claimed the power to declare it unconstitutional and did so declare it.
LJSpeech-1.1/wavs/LJ048-0277.wav|He felt that each agent recognized the seriousness of the infraction and that there was no danger of a repetition.
LJSpeech-1.1/wavs/LJ018-0050.wav|His arguments were specious and evasive when pressed to confess. "Why should man confess to man?" he replied;
LJSpeech-1.1/wavs/LJ018-0170.wav|On the bed were twenty forged ten-pound notes complete and ready for use, and twenty-five five-pound notes.
LJSpeech-1.1/wavs/LJ017-0163.wav|either arsenic or antimony, or both, in small quantities,
LJSpeech-1.1/wavs/LJ003-0149.wav|supported themselves; they had the ration of prison bread only,
LJSpeech-1.1/wavs/LJ016-0268.wav|The remarks heard amongst the crowd were of coarse approval.
LJSpeech-1.1/wavs/LJ010-0180.wav|the Prince too rose to shield her with his person. Again, providentially, the bullet went wide of the mark,
LJSpeech-1.1/wavs/LJ030-0183.wav|As he told the driver, quote, Let's get out of here; we are hit, end quote,
LJSpeech-1.1/wavs/LJ014-0027.wav|A woman whom he called on the same evening declared he had worn a mackintosh, his coat was much torn, there was a stain of blood on his shirt-cuff,
LJSpeech-1.1/wavs/LJ039-0011.wav|toward any official of the United States.
LJSpeech-1.1/wavs/LJ016-0158.wav|It was that of a "Long Firm" swindler, by name Johnson,
LJSpeech-1.1/wavs/LJ048-0213.wav|watching his car, watching the sides, watching the crowds, giving advice or asking advice from the Chief
LJSpeech-1.1/wavs/LJ046-0050.wav|administrative, political.
LJSpeech-1.1/wavs/LJ019-0306.wav|while twenty-seven received less than six prisoners, and were in some instances absolutely tenantless.
LJSpeech-1.1/wavs/LJ030-0076.wav|It carried eight Secret Service agents -- two in the front seat, two in the rear, and two on each of the right and left running boards.
LJSpeech-1.1/wavs/LJ024-0005.wav|has reached the age of seventy and does not avail himself of the opportunity to retire on a pension,
LJSpeech-1.1/wavs/LJ004-0099.wav|Ventilators, hand and others, were to be supplied.
LJSpeech-1.1/wavs/LJ030-0113.wav|through thinly populated areas on the outskirts of Dallas.
LJSpeech-1.1/wavs/LJ019-0009.wav|or to insist upon the construction of prisons on the most approved plan.
LJSpeech-1.1/wavs/LJ048-0287.wav|It is conceivable that those men who had little sleep, and who had consumed alcoholic beverages, even in limited quantities,
LJSpeech-1.1/wavs/LJ023-0090.wav|It is the accusation of most distinguished justices of the present Supreme Court.
LJSpeech-1.1/wavs/LJ039-0198.wav|but to determine the maximum speed at which it could be fired.
LJSpeech-1.1/wavs/LJ016-0042.wav|The condition of the stone surface just mentioned assisted him in this, and he managed to get beyond the cistern to the railing below the chevaux-de-frise.
LJSpeech-1.1/wavs/LJ049-0116.wav|of such persons as have been constitutionally and lawfully provided to succeed thereto in case of a vacancy. It is important to this country
LJSpeech-1.1/wavs/LJ016-0400.wav|Wainwright's demeanor was one of reckless effrontery steadily maintained to the last.
LJSpeech-1.1/wavs/LJ048-0236.wav|There is no indication that any of the agents who visited the Cellar Coffee House had any intoxicating drink at that establishment.
LJSpeech-1.1/wavs/LJ008-0264.wav|But the murderers formed only a small proportion of the total number sentenced to death, and for the rest there was a long period of anxious suspense,
LJSpeech-1.1/wavs/LJ039-0165.wav|The target at two hundred sixty-five feet was placed to the right of the two hundred forty-foot target
LJSpeech-1.1/wavs/LJ035-0150.wav|As she approached her desk, she saw Oswald.
LJSpeech-1.1/wavs/LJ009-0199.wav|About this time I find that the bodies of two murderers, Clench and Mackay,
LJSpeech-1.1/wavs/LJ028-0516.wav|the strongest, the thickest, the loftiest, the most intricate, perhaps the most beautiful that ever protected a city,
LJSpeech-1.1/wavs/LJ042-0150.wav|Marina Oswald's judgment of her husband's state of mind may be substantiated by comparing material which he wrote in the Soviet Union
LJSpeech-1.1/wavs/LJ035-0081.wav|The second test followed immediately after the first.
LJSpeech-1.1/wavs/LJ013-0009.wav|This was the willful shipwreck and casting away of a vessel which, with her supposed cargo, had been heavily insured.
LJSpeech-1.1/wavs/LJ047-0232.wav|In his opinion, none of the information in the FBI files -- Oswald's defection, his Fair Play for Cuba activities in New Orleans,
LJSpeech-1.1/wavs/LJ006-0028.wav|Mr. Crawford was thoroughly versed in the still imperfectly understood science of prison management, and fully qualified for his new duties.
LJSpeech-1.1/wavs/LJ019-0168.wav|Renewed recommendations to provide employment resulted in the provision of a certain amount of oakum for picking,
LJSpeech-1.1/wavs/LJ002-0030.wav|Full details of the arrangements are to be found in Mr. Neild's "State of Prisons in England, Scotland, and Wales," published in eighteen twelve.
LJSpeech-1.1/wavs/LJ031-0208.wav|The hospital received the President's body for autopsy at approximately seven:thirty-five p.m.
LJSpeech-1.1/wavs/LJ023-0108.wav|We are under a Constitution, but the Constitution is what the judges say it is.
LJSpeech-1.1/wavs/LJ032-0021.wav|was a distributor of surplus Italian six point five-millimeter military rifles. During the evening of November twenty-two, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ017-0171.wav|Smethurst was therefore given a free pardon for the offense of murder,
LJSpeech-1.1/wavs/LJ030-0096.wav|These agents performed for the Vice President the same functions that the agents in the Presidential follow-up car performed for the President.
LJSpeech-1.1/wavs/LJ015-0065.wav|Robson was of humble origin, but he was well educated, and he had some literary abilities.
LJSpeech-1.1/wavs/LJ032-0167.wav|He concluded, quote, There is no doubt in my mind that these fibers could have come from this shirt.
LJSpeech-1.1/wavs/LJ003-0265.wav|the thieves and burglars who carried on the active business of their profession, from which their confederates were temporarily debarred.
LJSpeech-1.1/wavs/LJ034-0218.wav|The Commission has determined that the employee was in fact Billy Lovelady, who identified himself in the picture.
LJSpeech-1.1/wavs/LJ028-0141.wav|so that the entire circuit is four hundred and eighty furlongs.
LJSpeech-1.1/wavs/LJ050-0140.wav|Secretary Dillon testified that the use of such liaison officers is the only effective way to insure that adequate liaison is maintained.
LJSpeech-1.1/wavs/LJ027-0115.wav|it will be suffered to dwindle away in successive generations, under the influence of certain natural causes.
LJSpeech-1.1/wavs/LJ009-0298.wav|which sets forth that the petitioner had been at great expense by sending clerks and agents to Liverpool and Shrewsbury to hire an executioner.
LJSpeech-1.1/wavs/LJ036-0008.wav|(one) positive identification of the killer by two eyewitnesses who saw the shooting
LJSpeech-1.1/wavs/LJ046-0019.wav|In this part of its inquiry the Commission has had full access to a major study of all phases of protective activities
LJSpeech-1.1/wavs/LJ001-0086.wav|are dazzling and unpleasant to the eye owing to the clumsy thickening and vulgar thinning of the lines:
LJSpeech-1.1/wavs/LJ010-0265.wav|and on his information handbills were circulated, giving the exact description of the deformed youth, who had a hump-back,
LJSpeech-1.1/wavs/LJ028-0154.wav|at the point where the city of the same name stands, eight days' journey from Babylon.
LJSpeech-1.1/wavs/LJ011-0285.wav|The door of his place of durance stood open, and Mr. Gee began to consider whether he might not escape.
LJSpeech-1.1/wavs/LJ047-0082.wav|for an extended tour of Western European countries, the Soviet Union, Finland, and Poland.
LJSpeech-1.1/wavs/LJ014-0100.wav|In the back kitchen one of the detectives remarked that the cement between certain stones looked lighter than the rest, and on trying it with a knife,
LJSpeech-1.1/wavs/LJ048-0272.wav|Chief Rowley testified
LJSpeech-1.1/wavs/LJ027-0057.wav|In all vertebrates, and in none other, the axis of this skeleton is a jointed backbone (vertebral column)
LJSpeech-1.1/wavs/LJ018-0062.wav|Christian Sattler was by birth a German.
LJSpeech-1.1/wavs/LJ015-0193.wav|By-and-by, when escape seemed hopeless, and after sentence, he suddenly degenerated into the lowest stamp of criminal,
LJSpeech-1.1/wavs/LJ004-0066.wav|or his health by forcing him at night into a damp, unventilated cell, with such crowds of companions as very speedily render the air foul and putrid;
LJSpeech-1.1/wavs/LJ018-0314.wav|Certain friends of the prisoners were watched, and found to be in communication with these warders,
LJSpeech-1.1/wavs/LJ034-0112.wav|The New Orleans police records of his arrest in August of nineteen sixty-three show a weight of one hundred thirty-six pounds.
LJSpeech-1.1/wavs/LJ031-0051.wav|He noted contusions, hematoma to the right of the larynx, which was deviated slightly to the left,
LJSpeech-1.1/wavs/LJ007-0025.wav|There were frequent quarrels and fights; shoes and other missiles were freely bandied about;
LJSpeech-1.1/wavs/LJ015-0148.wav|The choicest wines, the finest fruits,
LJSpeech-1.1/wavs/LJ045-0027.wav|During the period from Oswald's return from Mexico to the assassination,
LJSpeech-1.1/wavs/LJ047-0137.wav|On October three, Hosty reopened the case in Dallas to assist the New Orleans office.
LJSpeech-1.1/wavs/LJ002-0325.wav|or the sixpenny allowance was claimed for the creditors, which seldom happened, owing to the expense the process entailed.
LJSpeech-1.1/wavs/LJ045-0162.wav|He tried to start a conversation with me several times, but I would not answer. And he said that he didn't want me to be angry at him because this upsets him.
LJSpeech-1.1/wavs/LJ013-0096.wav|Suspicions were aroused when it was found that he had been employed in selling stock for Mr. Oxenford, which developed into certainty
LJSpeech-1.1/wavs/LJ031-0187.wav|Federal Judge Sarah T. Hughes hastened to the plane to administer the oath.
LJSpeech-1.1/wavs/LJ047-0009.wav|who interviewed Oswald after his return from the Soviet Union and prior to November twenty-two, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ013-0035.wav|While lying in Newgate, awaiting removal to the convict ship, both prisoners made full confessions.
LJSpeech-1.1/wavs/LJ021-0003.wav|Three months have passed since I talked with you shortly after the adjournment of the Congress.
LJSpeech-1.1/wavs/LJ023-0131.wav|We must have men worthy and equipped to carry out impartial justice.
LJSpeech-1.1/wavs/LJ016-0311.wav|that any secrecy in the treatment of the condemned would invest them with a new and greater interest, which was much to be deprecated.
LJSpeech-1.1/wavs/LJ045-0174.wav|Thank you. That it would be better if he bought something for himself -- that I would manage. End quote. That night Oswald went to bed before his wife retired.
LJSpeech-1.1/wavs/LJ030-0037.wav|are designed to provide protection while permitting large numbers of people to see the President.
LJSpeech-1.1/wavs/LJ034-0082.wav|None of the Depository employees is known to have seen Oswald again until after the shooting.
LJSpeech-1.1/wavs/LJ004-0194.wav|No irons were worn except as a punishment.
LJSpeech-1.1/wavs/LJ043-0108.wav|Oswald's employment problems became more difficult. He left his wife and child at the home of a friend, Mrs. Ruth Paine, of Irving, Texas.
LJSpeech-1.1/wavs/LJ039-0081.wav|Referring to a rifle with a four-power telescope, Sergeant Zahm said, quote,
LJSpeech-1.1/wavs/LJ040-0200.wav|Furthermore she did not appear to understand her own relationship to Lee's psychological problems.
LJSpeech-1.1/wavs/LJ025-0069.wav|innumerable plants and free plant cells are known to pass the whole or part of their lives in an actively locomotive condition,
LJSpeech-1.1/wavs/LJ008-0184.wav|Precautions had been taken by the erection of barriers, and the posting of placards at all the avenues to the Old Bailey, on which was printed,
LJSpeech-1.1/wavs/LJ003-0121.wav|But all punishments might readily be commuted into a fine to be spent in gin for judge and jury.
LJSpeech-1.1/wavs/LJ047-0163.wav|According to Hosty, Mrs. Paine indicated that she thought she could find out where Oswald was living and would let him know.
LJSpeech-1.1/wavs/LJ021-0065.wav|but also to the owners and managers of industry because,
LJSpeech-1.1/wavs/LJ005-0089.wav|The religious and moral welfare of the prisoners were to be attended to,
LJSpeech-1.1/wavs/LJ041-0130.wav|Probably his complaint was due to the fact that his discharge was not related to anything he had done while on active duty
LJSpeech-1.1/wavs/LJ036-0095.wav|but the Commission concluded that this man was not Lee Harvey Oswald,
LJSpeech-1.1/wavs/LJ030-0244.wav|hitting me on the shoulder, and shouted to all of us in the back seat to get down.
LJSpeech-1.1/wavs/LJ021-0184.wav|Great Britain in many ways has advanced further along lines of social security than the United States?
LJSpeech-1.1/wavs/LJ032-0247.wav|during the summer of nineteen sixty-three.
LJSpeech-1.1/wavs/LJ017-0022.wav|was that of Eliza Fenning, who was convicted of an attempt to poison a whole family
LJSpeech-1.1/wavs/LJ010-0141.wav|he was generally supposed to be a surgeon.
LJSpeech-1.1/wavs/LJ036-0042.wav|However, McWatters' recollection alone was too vague to be a basis for placing Oswald on the bus.
LJSpeech-1.1/wavs/LJ018-0281.wav|Their operations were no less worldwide.
LJSpeech-1.1/wavs/LJ044-0057.wav|extensive investigation was not able to connect Oswald with that address, although it did develop the fact
LJSpeech-1.1/wavs/LJ044-0033.wav|It is also evidence of Oswald's reluctance to describe events accurately
LJSpeech-1.1/wavs/LJ046-0210.wav|to relate principally to overt threats to harm the President or other specific manifestations of hostility.
LJSpeech-1.1/wavs/LJ024-0072.wav|a new and younger judge shall be added to the court automatically.
LJSpeech-1.1/wavs/LJ007-0107.wav|A resolution at once passed the House without division to commit the whole to Newgate, where they remained for various terms.
LJSpeech-1.1/wavs/LJ050-0191.wav|More importantly, the lack of carefully prepared and carefully transmitted instructions for typical visits to cities
LJSpeech-1.1/wavs/LJ020-0051.wav|Flour a rolling-pin and roll the dough into a sheet not more than half an inch thick.
LJSpeech-1.1/wavs/LJ016-0074.wav|The success, although very short-lived, which attended him, no doubt inspired other inmates of Newgate to follow his example.
LJSpeech-1.1/wavs/LJ031-0221.wav|When put together, these fragments accounted for approximately three-quarters of the missing portion of the skull.
LJSpeech-1.1/wavs/LJ015-0205.wav|who had been concerned in various "jobs" of a dishonest character, and who for the moment was a clerk in a betting office.
LJSpeech-1.1/wavs/LJ001-0104.wav|Italy is contentedly stagnant.
LJSpeech-1.1/wavs/LJ001-0157.wav|of this it may be said that though there is some good paper made now,
LJSpeech-1.1/wavs/LJ047-0192.wav|On November eighteen the FBI learned that Oswald recently had been in communication with the Soviet Embassy in Washington
LJSpeech-1.1/wavs/LJ001-0006.wav|And it is worth mention in passing that, as an example of fine typography,
LJSpeech-1.1/wavs/LJ048-0100.wav|who had just completed advance work on the President's trip to Tampa.
LJSpeech-1.1/wavs/LJ012-0004.wav|Inquiries set on foot also elicited the suspicion that the person who had represented Mrs. Canning's brother
LJSpeech-1.1/wavs/LJ008-0086.wav|A great concourse of people attended on this melancholy occasion.
LJSpeech-1.1/wavs/LJ023-0061.wav|that they were all the powers needed to meet each and every problem which then had a national character
LJSpeech-1.1/wavs/LJ012-0255.wav|These were the missing members of the same mutilated trunk,
LJSpeech-1.1/wavs/LJ018-0112.wav|It was one of these, Glendinning, who had allowed himself to be utilized for some time in this way, whose capture led to the breaking up of the gang.
LJSpeech-1.1/wavs/LJ049-0052.wav|In response to inquiry by the Commission regarding the instructions to agents in a motorcade
LJSpeech-1.1/wavs/LJ030-0026.wav|Governor and Mrs. Connally and Senator Ralph W. Yarborough had come with the President from Fort Worth.
LJSpeech-1.1/wavs/LJ037-0085.wav|She was not sure whether she had seen his picture in a newspaper on the afternoon or evening of November twenty-two prior to the lineup.
LJSpeech-1.1/wavs/LJ014-0092.wav|The hole must have been excavated and the quicklime purchased quite three weeks before O'Connor met his death,
LJSpeech-1.1/wavs/LJ050-0014.wav|The incumbent has no technical qualifications in the area of Presidential protection.
LJSpeech-1.1/wavs/LJ040-0203.wav|but essentially a, quote, defensive, rigid, self-involved person
LJSpeech-1.1/wavs/LJ033-0026.wav|There was little conversation between them on the way home.
LJSpeech-1.1/wavs/LJ043-0084.wav|business suit, alert replies -- Expresses self extremely well, end quote.
LJSpeech-1.1/wavs/LJ022-0200.wav|renewed faith in the vast possibilities of human beings to improve their material and spiritual status
LJSpeech-1.1/wavs/LJ008-0030.wav|The first affair of the kind on this spot was on the third December, seventeen eighty-three,
LJSpeech-1.1/wavs/LJ044-0199.wav|In retrospect his attempt to go to Cuba or return to the Soviet Union may well have been Oswald's last escape hatch,
LJSpeech-1.1/wavs/LJ029-0046.wav|Preventive Intelligence Activities. The Protective Research Section (PRS) of the Secret Service
LJSpeech-1.1/wavs/LJ002-0048.wav|two. The female debtors' side consisted of a court-yard forty-nine by sixteen feet,
LJSpeech-1.1/wavs/LJ029-0026.wav|it was agreed that the planning of events in Texas would be left largely to the Governor.
LJSpeech-1.1/wavs/LJ050-0068.wav|According to Chief Rowley, by mid-June nineteen sixty-four,
LJSpeech-1.1/wavs/LJ012-0171.wav|Every door had been closed against him, every hope of future support blasted.
LJSpeech-1.1/wavs/LJ042-0245.wav|While Marina Oswald tried to obtain permission to return to the Soviet Union, she testified that she did so at her husband's insistence.
LJSpeech-1.1/wavs/LJ028-0353.wav|Darius, as the story goes, would often say that "he had rather Zopyrus were unmaimed, than be master of twenty more Babylons."
LJSpeech-1.1/wavs/LJ006-0199.wav|the most popular being the "Times," "Morning Herald," and "Morning Chronicle"; on Sunday the "Weekly Dispatch," "Bell's Life," and the "Weekly Messenger."
LJSpeech-1.1/wavs/LJ005-0209.wav|through the bars of which quills or reeds were inserted, and drink conveyed to the prisoners.
LJSpeech-1.1/wavs/LJ005-0136.wav|The want of sleeping cells long continued a crying need.
LJSpeech-1.1/wavs/LJ003-0179.wav|which will deal with Mrs. Fry's philanthropic exertions at this period in this particular part of the prison.
LJSpeech-1.1/wavs/LJ034-0004.wav|Lee Harvey Oswald was hired on October fifteen, nineteen sixty-three, by the Texas School Book Depository as an "order filler."
LJSpeech-1.1/wavs/LJ028-0182.wav|and in five fifty-five Nabonidus, the father of the Biblical Belshazzar, came to the throne.
LJSpeech-1.1/wavs/LJ035-0007.wav|The encounter in the lunchroom.
LJSpeech-1.1/wavs/LJ027-0131.wav|of descent discovered in the development of plant and animal embryos.
LJSpeech-1.1/wavs/LJ013-0227.wav|The order was, however, at length obeyed, and the whole of the prisoner's clothes were minutely searched.
LJSpeech-1.1/wavs/LJ039-0179.wav|stated that there was a shorter interval between shots two and three than between shots one and two.
LJSpeech-1.1/wavs/LJ010-0057.wav|are by this time actually, and by more legitimate efforts, engrafted upon our Constitution.
LJSpeech-1.1/wavs/LJ040-0115.wav|Pic and his wife would have been happy to have kept Lee, however,
LJSpeech-1.1/wavs/LJ023-0006.wav|Tonight, sitting at my desk in the White House, I make my first radio report to the people in my second term of office.
LJSpeech-1.1/wavs/LJ033-0148.wav|Using a standard chemical method involving silver nitrates
LJSpeech-1.1/wavs/LJ016-0262.wav|It was a callous, careless crowd of coarse-minded, semi-brutalized folk, who came to enjoy themselves.
LJSpeech-1.1/wavs/LJ011-0258.wav|The defense he set up was, that Mullay had used epithets towards him while they were negotiating a business matter,
LJSpeech-1.1/wavs/LJ013-0050.wav|But among the charges on the estate he left
LJSpeech-1.1/wavs/LJ002-0149.wav|The latter indeed hung like millstones round the neck of the unhappy insolvent wretches who found themselves in limbo.
LJSpeech-1.1/wavs/LJ016-0416.wav|Many, like Wainwright, were calm and imperturbable throughout their trying ordeal.
LJSpeech-1.1/wavs/LJ040-0111.wav|with no behavior or truancy problems.
LJSpeech-1.1/wavs/LJ012-0045.wav|he put another lady, with whom he was on intimate terms.
LJSpeech-1.1/wavs/LJ038-0234.wav|Although Oswald destroyed the notebook, three photographs found among Oswald's possessions after the assassination
LJSpeech-1.1/wavs/LJ002-0134.wav|The County Court was the sheriff's, who sat there surrounded by the bishop and the magnates of the county;
LJSpeech-1.1/wavs/LJ038-0247.wav|A fourth photograph, showing a stretch of railroad tracks,
LJSpeech-1.1/wavs/LJ004-0001.wav|The Chronicles of Newgate, Volume two. By Arthur Griffiths. Section seven: The beginnings of prison reform.
LJSpeech-1.1/wavs/LJ038-0132.wav|When asked why he lived at his roominghouse under the name O. H. Lee,
LJSpeech-1.1/wavs/LJ042-0240.wav|he continued to be interested in that country after he returned to the United States.
LJSpeech-1.1/wavs/LJ034-0100.wav|this man I saw previously was aiming for his last shot. As it appeared to me he was standing up and resting against the left window sill, end quote.
LJSpeech-1.1/wavs/LJ014-0228.wav|generally known by the soubriquet of "General Haynau," a name execrated in England about this time.
LJSpeech-1.1/wavs/LJ018-0103.wav|and silver coins, with all the latest appliances for coining, including those of electroplating;
LJSpeech-1.1/wavs/LJ038-0217.wav|indicated that the note was written when they were living in a rented apartment; therefore it could not have been written while Marina Oswald was living with the Paines.
LJSpeech-1.1/wavs/LJ050-0222.wav|would take approximately twenty months to implement and require expenditures of approximately three million dollars during that period.
LJSpeech-1.1/wavs/LJ001-0050.wav|and though the famous family of Aldus restored its technical excellence, rejecting battered letters,
LJSpeech-1.1/wavs/LJ010-0170.wav|His acquaintances often asked his object in this, but he kept his own counsel till the tenth June.
LJSpeech-1.1/wavs/LJ028-0284.wav|When he found that Darius did indeed value it highly, he considered further with himself how he might make the deed his own, and be the man to take Babylon.
LJSpeech-1.1/wavs/LJ019-0351.wav|Nor were these the only inducements offered. Where local authorities were indisposed to set their prisons in order,
LJSpeech-1.1/wavs/LJ030-0218.wav|the right rear tail, when she noticed that I was trying to climb on the car.
LJSpeech-1.1/wavs/LJ012-0030.wav|Thus, a watch was paid for as a watch, whether it was of gold or silver; a piece of linen as such, whether the stuff was coarse or fine.
LJSpeech-1.1/wavs/LJ042-0244.wav|Oswald subsequently did subscribe to several Soviet journals.
LJSpeech-1.1/wavs/LJ035-0043.wav|Yet he must have entered the vestibule door before Truly reached the top of the stairwell, since Truly did not see him.
LJSpeech-1.1/wavs/LJ018-0068.wav|Inspector Thain, who, being unable to obtain his extradition legally, had him inveigled on board an English steamer,
LJSpeech-1.1/wavs/LJ023-0091.wav|I have not the time to quote to you all the language used by dissenting justices in many of these cases.
LJSpeech-1.1/wavs/LJ022-0005.wav|It has made and is making distinct progress.
LJSpeech-1.1/wavs/LJ028-0178.wav|the walls of Babylon were so long and wide and high that all who saw them were amazed.
LJSpeech-1.1/wavs/LJ050-0193.wav|Such instructions will not fit all circumstances, of course,
LJSpeech-1.1/wavs/LJ029-0212.wav|"Welcome Mr. Kennedy to Dallas," sponsored by the American Fact-finding Committee, which the sponsor later testified was an ad hoc committee
LJSpeech-1.1/wavs/LJ019-0063.wav|who maintained that under this system prisoners were more industrious and more healthy
LJSpeech-1.1/wavs/LJ019-0126.wav|The creation of an expensive staff for supervision,
LJSpeech-1.1/wavs/LJ045-0237.wav|His denials under questioning, which have no probative value in view of the many readily demonstrable lies he told at that time
LJSpeech-1.1/wavs/LJ042-0007.wav|At the age of nineteen, Oswald thus committed an act which was the most striking indication he had yet given
LJSpeech-1.1/wavs/LJ047-0143.wav|The possible contact with the Soviet Embassy in Mexico intensified the FBI's interest in learning Oswald's whereabouts.
LJSpeech-1.1/wavs/LJ049-0176.wav|On the other hand, the Secret Service had no knowledge whatever of Oswald, his background, or his employment at the Book Depository,
LJSpeech-1.1/wavs/LJ050-0232.wav|to assist in its protection functions.
LJSpeech-1.1/wavs/LJ008-0017.wav|and when he evaded the sentence by suicide, his body was exhibited in the same neighborhood,
LJSpeech-1.1/wavs/LJ042-0072.wav|Still intent, however, on staying in the Soviet Union,
LJSpeech-1.1/wavs/LJ010-0245.wav|one of the equerries. The Queen was untouched, and at first, it is said, hardly realized the danger she had escaped.
LJSpeech-1.1/wavs/LJ006-0260.wav|From the same source came the two or three strong files which the inspectors found in one ward,
LJSpeech-1.1/wavs/LJ027-0165.wav|Now, the lower forms of amphibians, such as siredon, menobranchus, siren, etc.,
LJSpeech-1.1/wavs/LJ033-0192.wav|When Paul M. Stombaugh of the FBI Laboratory examined the paper bag,
LJSpeech-1.1/wavs/LJ018-0117.wav|Wagner, after conviction, offered to reveal, for a reward of three thousand pounds
LJSpeech-1.1/wavs/LJ003-0271.wav|Some of the worst and most extensive burglaries were planned there.
LJSpeech-1.1/wavs/LJ008-0068.wav|But the fall apart and inwards of two leaves is considered superior.
LJSpeech-1.1/wavs/LJ018-0152.wav|With her assistance on a certain day a couple of bricks were taken out of the wall dividing her front and back parlors;
LJSpeech-1.1/wavs/LJ019-0396.wav|At a short distance stood another prison of detention, that of Clerkenwell,
LJSpeech-1.1/wavs/LJ016-0338.wav|inside the jail was Colonel Frazer, the chief commissioner of the city police, and at no great distance, although in the background,
LJSpeech-1.1/wavs/LJ021-0089.wav|and have effected a reorganization of the N.R.A.
LJSpeech-1.1/wavs/LJ044-0230.wav|His unhappy experience with the Cuban consul seems thus to have reduced his enthusiasm for the Castro regime and his desire to go to Cuba.
LJSpeech-1.1/wavs/LJ018-0133.wav|which gave him access to all parts of the mills, the packing-room included.
LJSpeech-1.1/wavs/LJ039-0190.wav|Simmons testified that familiarity with the bolt could be achieved in dry practice and, as has been indicated above,
LJSpeech-1.1/wavs/LJ050-0250.wav|The Secret Service will be better able to plan its own long-range personnel requirements if it knows with reasonable certainty
LJSpeech-1.1/wavs/LJ040-0168.wav|She thought that he had detached himself from the world around him because, quote, no one in it ever met any of his needs for love, end quote.
LJSpeech-1.1/wavs/LJ010-0097.wav|Here they were surprised by the police, headed by a magistrate, and supported by a strong detachment of Her Majesty's Guards.
LJSpeech-1.1/wavs/LJ040-0064.wav|This occurred two months before Lee was born in New Orleans on October eighteen, nineteen thirty-nine.
LJSpeech-1.1/wavs/LJ050-0199.wav|The Commission strongly encourages these efforts to improve protection along a motorcade route.
LJSpeech-1.1/wavs/LJ028-0322.wav|Thus did Zopyrus speak.
LJSpeech-1.1/wavs/LJ008-0208.wav|Some years later an eye-witness published a graphic account of one of these scenes.
LJSpeech-1.1/wavs/LJ027-0023.wav|that the only reasonable explanation for the existence of a fundamental unity in organic life
LJSpeech-1.1/wavs/LJ012-0170.wav|According to his statement, when sentenced to death, he had been driven to horse-stealing by the execration which had pursued him after the murder.
LJSpeech-1.1/wavs/LJ003-0242.wav|was still practiced, that of loading newly-arrived prisoners until they paid certain fees.
LJSpeech-1.1/wavs/LJ007-0213.wav|Again the following year the inspectors repeat their charge.
LJSpeech-1.1/wavs/LJ014-0108.wav|It was soon ascertained that the wife had gone off in a cab with a quantity of luggage.
LJSpeech-1.1/wavs/LJ035-0151.wav|He was walking into the office from the back hallway,
LJSpeech-1.1/wavs/LJ010-0253.wav|The enthusiasm of the people at the Queen's escape was uproarious, and her drive next day was one long triumphal progress.
LJSpeech-1.1/wavs/LJ001-0116.wav|still clings to a foolish, because misunderstood conventionality, deduced from what was once ornament, and is by no means useful;
LJSpeech-1.1/wavs/LJ041-0203.wav|to engage in activities on behalf of the Fair Play for Cuba Committee in the summer of nineteen sixty-three,
LJSpeech-1.1/wavs/LJ030-0195.wav|Observing his blood-covered chest as he was pulled into his wife's lap, Governor Connally believed himself mortally wounded.
LJSpeech-1.1/wavs/LJ045-0119.wav|which had led to the disclosure of his defection in New Orleans.
LJSpeech-1.1/wavs/LJ019-0359.wav|He could in the first place withhold the government grant in aid of prison funds by refusing the certificate to the Treasury upon which the allowance was paid.
LJSpeech-1.1/wavs/LJ001-0174.wav|should be a part of the whole scheme of the book.
LJSpeech-1.1/wavs/LJ037-0148.wav|in Oswald's possession to the exclusion of all other weapons.
LJSpeech-1.1/wavs/LJ009-0260.wav|The spectacle was horrible;
LJSpeech-1.1/wavs/LJ028-0152.wav|In the circuit of the wall are a hundred gates, all of brass, with brazen lintels and sideposts.
LJSpeech-1.1/wavs/LJ031-0108.wav|Rubber tubes were inserted between the second and third ribs to reexpand the right lung, which had collapsed because of the opening in the chest wall.
LJSpeech-1.1/wavs/LJ005-0298.wav|to the county jails from such prisons as were past improvement, and that the borough funds should be charged for the accommodation.
LJSpeech-1.1/wavs/LJ020-0087.wav|One word with regard to getting up early in order to give dough a chance for the second rising.
LJSpeech-1.1/wavs/LJ005-0069.wav|Absence of embellishment is in perfect unison with the character of the establishment.
LJSpeech-1.1/wavs/LJ003-0328.wav|Had they been accepted in their entirety, little fault could in future have been found with the managers of Newgate.
LJSpeech-1.1/wavs/LJ007-0008.wav|their especial care.
LJSpeech-1.1/wavs/LJ048-0134.wav|would be a desirable innovation.
LJSpeech-1.1/wavs/LJ046-0134.wav|In the period from November nineteen sixty-one to November nineteen sixty-three,
LJSpeech-1.1/wavs/LJ008-0016.wav|Lawrence Jones, a burglar, was in seventeen ninety-three ordered for execution in Hatton Garden, near the house he had robbed;
LJSpeech-1.1/wavs/LJ019-0277.wav|the prisoners should be made to dispense with the use of a mattress, and should sleep on planks.
LJSpeech-1.1/wavs/LJ012-0133.wav|The fraudulent messenger, by the help of young Caspar, established his claim to the boxes, paid the wharfage dues, and carried off the gold-dust.
LJSpeech-1.1/wavs/LJ028-0086.wav|the lips are thin, the chin prominent; the neck is that of a strong vigorous man.
LJSpeech-1.1/wavs/LJ047-0204.wav|Bouck pointed to a number of characteristics besides Oswald's defection the cumulative effect of which would have been to alert the Secret Service
LJSpeech-1.1/wavs/LJ019-0106.wav|His plan was to devote the whole labor of prisoners sentenced to any term between three months and four years to agriculture.
LJSpeech-1.1/wavs/LJ040-0120.wav|Lee refused to discuss the matter with Pic, whom he had previously idolized, and their relations were strained thereafter.
LJSpeech-1.1/wavs/LJ025-0058.wav|but the fact, important as it was, fell into oblivion and had to be rediscovered by Treviranus in eighteen oh seven.
LJSpeech-1.1/wavs/LJ035-0118.wav|They rushed to the west windows after the shots were fired and remained there
LJSpeech-1.1/wavs/LJ009-0129.wav|that many of the kneeling men or boys laughed while they knelt, pinched each other, and, when they could do so without fear of being seen by any officer of the prison,
LJSpeech-1.1/wavs/LJ019-0340.wav|The latter was rendered nearly impossible by the penalties imposed on persons bringing spirituous liquors into the jail.
LJSpeech-1.1/wavs/LJ048-0223.wav|After the President had retired at his hotel,
LJSpeech-1.1/wavs/LJ019-0325.wav|the ministrations of ministers of their own form of belief.
LJSpeech-1.1/wavs/LJ035-0098.wav|he was certain that both elevators, which occupy the same shaft, were on the fifth floor.
LJSpeech-1.1/wavs/LJ016-0325.wav|The judge of the Admiralty Court, the Right Hon. Stephen Lushington, the Right Hon. James Moncrieff,
LJSpeech-1.1/wavs/LJ034-0216.wav|In the background of this picture were several employees watching the parade from the steps of the Depository Building.
LJSpeech-1.1/wavs/LJ017-0101.wav|That day Palmer had bought more strychnia, and had called in a fresh doctor.
LJSpeech-1.1/wavs/LJ022-0099.wav|to move as rapidly as possible back into private employment when such employment is available.
LJSpeech-1.1/wavs/LJ033-0115.wav|I remember that I didn't look at the package very much but when I did look at it he did have his hands on the package like that, end quote, and at this point
LJSpeech-1.1/wavs/LJ049-0072.wav|those in command should be able to direct the response appropriate to the emergency. The Commission finds that the Secret Service agents in the motorcade
LJSpeech-1.1/wavs/LJ021-0100.wav|Let me call your attention to the fact that the national Industrial Recovery Act
LJSpeech-1.1/wavs/LJ016-0156.wav|at no elevation affords the only drop, strangulation would seldom supervene but for the resolution of the miserable felo de se.
LJSpeech-1.1/wavs/LJ010-0291.wav|Pate was found guilty, and sentenced to seven years' transportation, the judge, Baron Alderson, abstaining from inflicting the penalty of whipping,
LJSpeech-1.1/wavs/LJ037-0172.wav|even though only four bullets were recovered.
LJSpeech-1.1/wavs/LJ044-0229.wav|and had lost his desire to do so because of the bureaucracy and red tape which he had encountered.
LJSpeech-1.1/wavs/LJ049-0217.wav|Moreover, a number of imponderable questions have to be weighed if any change in the intimate association now established
LJSpeech-1.1/wavs/LJ039-0194.wav|All three of the firers in these tests
LJSpeech-1.1/wavs/LJ003-0256.wav|By this means spirits, otherwise unattainable and strictly prohibited, were smuggled into the jail.
LJSpeech-1.1/wavs/LJ050-0171.wav|but it seems to warrant further study before each agency becomes irrevocably committed to separate action.
LJSpeech-1.1/wavs/LJ050-0151.wav|it makes no use of the recent developments in automatic data processing which are widely used in the business world and in other Government offices.
LJSpeech-1.1/wavs/LJ017-0211.wav|which left London for Singapore on the twenty-eighth July, eighteen sixty-three, with a cargo of wine and other goods.
LJSpeech-1.1/wavs/LJ003-0181.wav|There was a master's side for females who could pay the usual fees, but they associated with the rest in the one narrow yard common to all.
LJSpeech-1.1/wavs/LJ035-0051.wav|He saw a man walking away from him in the lunchroom.
LJSpeech-1.1/wavs/LJ022-0187.wav|but these twenty years have shown by experience definite possibilities for improvement.
LJSpeech-1.1/wavs/LJ013-0204.wav|he admitted that he had been justly convicted, and expressed great anxiety that his fellow-servants should be relieved from all suspicion.
LJSpeech-1.1/wavs/LJ039-0113.wav|as a, quote, rather poor shot, end quote.
LJSpeech-1.1/wavs/LJ014-0032.wav|as the seducer of an innocent girl to whom he (Hocker) had been fondly attached.
LJSpeech-1.1/wavs/LJ045-0154.wav|Answer: He said that he was lonely because he hadn't come the preceding weekend, and he wanted to make his peace with me.
LJSpeech-1.1/wavs/LJ013-0206.wav|Next morning he made a full confession in presence of his attorney, and the governor, Mr. Cope.
LJSpeech-1.1/wavs/LJ021-0205.wav|I believe with Abraham Lincoln, that "The legitimate object of government is to do for a community of people
LJSpeech-1.1/wavs/LJ003-0260.wav|Another frightful consequence of this indiscriminate admission was the influx of numbers of abandoned women,
LJSpeech-1.1/wavs/LJ030-0044.wav|Motorcycles. -- Next came four to six motorcycle policemen whose main purpose was to keep the crowd back.
LJSpeech-1.1/wavs/LJ034-0143.wav|but he said he was unable to make a positive identification.
LJSpeech-1.1/wavs/LJ033-0150.wav|Sebastian F. Latona, supervisor of the FBI's Latent Fingerprint Section,
LJSpeech-1.1/wavs/LJ012-0144.wav|and passed it on to Solomons by his daughter, a widow named Abrahams.
LJSpeech-1.1/wavs/LJ004-0094.wav|This act set forth that "whereas the malignant fever commonly called the jail distemper
LJSpeech-1.1/wavs/LJ015-0113.wav|followed him over to Sweden, and arrested him at Helsingfors.
LJSpeech-1.1/wavs/LJ047-0179.wav|Hosty did nothing further in connection with the Oswald case until after the assassination. On November one, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ010-0292.wav|which was authorized by a recent act, on account of Mr. Pate's family and position in life.
LJSpeech-1.1/wavs/LJ013-0187.wav|near it was his Waterloo medal, and the above-mentioned ten-pound note.
LJSpeech-1.1/wavs/LJ049-0216.wav|the FBI, the CIA, and the military intelligence agencies as well as the Secret Service.
LJSpeech-1.1/wavs/LJ006-0248.wav|Matters were at times still worse, and the rioting went on to such dangerous lengths as to endanger the safety of the building.
LJSpeech-1.1/wavs/LJ031-0087.wav|When asked why he did not turn the President over, Dr. Carrico testified as follows:
LJSpeech-1.1/wavs/LJ004-0201.wav|At Ilchester the rule of employment had been carried further.
LJSpeech-1.1/wavs/LJ025-0092.wav|It is now established that nitrogen is as essential a constituent of vegetable as of animal living matter
LJSpeech-1.1/wavs/LJ016-0170.wav|greater attention was paid to the capital convicts, and the horrors of their situation while awaiting sentence
LJSpeech-1.1/wavs/LJ007-0243.wav|It was not till the erection of the new prison at Holloway in eighteen fifty, and the entire internal reconstruction of Newgate according to new ideas,
LJSpeech-1.1/wavs/LJ050-0166.wav|The Commission was struck by the apparent lack of effort, on an interagency basis,
LJSpeech-1.1/wavs/LJ040-0209.wav|well I've got to live with her. I guess I love her, end quote.
LJSpeech-1.1/wavs/LJ002-0075.wav|and who are therefore lodged apart from all other districts of the jail. End quote.
LJSpeech-1.1/wavs/LJ016-0213.wav|The origin of this expression dates, it is said, from the time when the Scottish mark,
LJSpeech-1.1/wavs/LJ001-0146.wav|which requires the constant exercise of judgment and taste on the part of the printer.
LJSpeech-1.1/wavs/LJ027-0040.wav|between the fin of a fish and the paddle of a whale
LJSpeech-1.1/wavs/LJ029-0097.wav|and on their return to Dallas drove over the route which Sorrels believed best suited for the proposed motorcade.
LJSpeech-1.1/wavs/LJ022-0104.wav|and the experience and the competence necessary to carry on the two hundred and fifty or three hundred kinds of work that will be undertaken.
LJSpeech-1.1/wavs/LJ005-0031.wav|no visiting of friends, no education but religious education, no freedom of diet,
LJSpeech-1.1/wavs/LJ032-0233.wav|reinforce the belief that the rifle in the photograph is the rifle which Oswald bought from Klein's.
LJSpeech-1.1/wavs/LJ028-0429.wav|The excavations have shown that Babylon, as the ancients told us, was nearly square.
LJSpeech-1.1/wavs/LJ049-0032.wav|had no special design or equipment which would have permitted the Secret Service agent riding in the driver's compartment
LJSpeech-1.1/wavs/LJ025-0139.wav|converge toward the conclusion that the nerve fibers, which have been regarded as ultimate elements of nervous tissue,
LJSpeech-1.1/wavs/LJ011-0037.wav|Appeals were made to the Home Secretary, and all possible political interest brought to bear, but without success.
LJSpeech-1.1/wavs/LJ002-0151.wav|Neild found at his visit to Newgate in eighteen ten,
LJSpeech-1.1/wavs/LJ044-0181.wav|The Cubans would not, however, give him a visa until he had received one from the Soviets, which involved a delay of several months.
LJSpeech-1.1/wavs/LJ033-0132.wav|I didn't pay too much attention the way he was walking because I was walking along there looking at the railroad cars and watching the men on the diesel switch them cars
LJSpeech-1.1/wavs/LJ036-0040.wav|In a later interview, Jones confirmed that he had exchanged words with a woman passenger on the bus during the ride south on Marsalis.
LJSpeech-1.1/wavs/LJ039-0195.wav|were able to fire the rounds within the time period which would have been available to the assassin under those conditions.
LJSpeech-1.1/wavs/LJ003-0298.wav|for giving every prisoner a sleeping cell to himself, an amount of enlightenment which is hardly general among European nations at this
LJSpeech-1.1/wavs/LJ047-0149.wav|the New Orleans office of the FBI learned that in September Oswald had given a forwarding address of two five one five
LJSpeech-1.1/wavs/LJ033-0083.wav|Oswald gripped the bag in his right hand near the top, quote, It tapered like this as he hugged it in his hand.
LJSpeech-1.1/wavs/LJ049-0138.wav|and, if the Council is used, arrangements should be made for the attendance of the Secretary of the Treasury
LJSpeech-1.1/wavs/LJ023-0141.wav|can, if they choose, hold office for life, no matter how old they may get to be.
LJSpeech-1.1/wavs/LJ015-0044.wav|with money enough to retrieve the position of the bank. But that passed from bad to worse;
LJSpeech-1.1/wavs/LJ021-0111.wav|There may be a serious question as to the wisdom of many of those devices to control production,
LJSpeech-1.1/wavs/LJ002-0097.wav|they had dust-bins, sewers, and so forth, "properly disposed," and the city scavenger paid periodical visits to the prison.
LJSpeech-1.1/wavs/LJ012-0085.wav|The chest was opened to give change, and a heavy tray lifted out which plainly held some four thousand pounds in cash.
LJSpeech-1.1/wavs/LJ018-0179.wav|On his return to Newgate to be finally discharged, Cummings jumped up the stairs and fairly danced for joy.
LJSpeech-1.1/wavs/LJ016-0402.wav|No woman could resist him, he calmly assured Mr. Smith that night as they walked together, and he recounted his villanies one by one.
LJSpeech-1.1/wavs/LJ037-0082.wav|On the evening of November twenty-two,
LJSpeech-1.1/wavs/LJ010-0114.wav|His sudden access to means unlimited was no doubt due to the profitable role he soon adopted of Government informer and spy,
LJSpeech-1.1/wavs/LJ019-0068.wav|Separation was injurious to health, mental or physical, said one side; men broke down when subjected to it for more than a certain period,
LJSpeech-1.1/wavs/LJ045-0037.wav|after his recent rebuffs in Mexico City
LJSpeech-1.1/wavs/LJ004-0205.wav|Industrial labor had also been introduced with satisfactory results.
LJSpeech-1.1/wavs/LJ035-0027.wav|They went through the swinging door and continued at, quote, a good trot, end quote,
LJSpeech-1.1/wavs/LJ034-0121.wav|twenty-seven, five foot eleven, one hundred sixty-five pounds, black wavy hair, end quote,
LJSpeech-1.1/wavs/LJ001-0047.wav|Of Jenson it must be said that he carried the development of Roman type as far as it can go:
LJSpeech-1.1/wavs/LJ019-0176.wav|The wards had open fires, but the separate cells were not warmed at all.
LJSpeech-1.1/wavs/LJ020-0061.wav|Break the rolls apart from one another and eat warm. They are also good cold, and if the directions be followed implicitly, very good always.
LJSpeech-1.1/wavs/LJ033-0095.wav|Frazier testified that Oswald carried no lunch bag that day.
LJSpeech-1.1/wavs/LJ028-0195.wav|It is a long story. Poets have sung it. Historians have written it. Prophets have preached it. Legends have gathered about it.
LJSpeech-1.1/wavs/LJ011-0288.wav|Thus free, he eluded the vigilance of two of the party, who were at dinner in the front kitchen,
LJSpeech-1.1/wavs/LJ009-0045.wav|he steps boldly with head upright, looks to the women's gallery, and smiles. His intention is to pass for a brave fellow,
LJSpeech-1.1/wavs/LJ027-0064.wav|All vertebrates, and none other, have two cavities,
LJSpeech-1.1/wavs/LJ037-0218.wav|Marina Oswald testified that this was the holster which contained the revolver in the photographs taken on Neely Street.
LJSpeech-1.1/wavs/LJ049-0048.wav|and therefore approximately one point six seconds after the President was shot in the head.
LJSpeech-1.1/wavs/LJ050-0156.wav|this money would be used to compensate consultants, to lease standard equipment or to purchase specially designed pilot equipment.
LJSpeech-1.1/wavs/LJ006-0222.wav|and enlivened by flash songs and thrilling long-winded descriptions of robberies and other "plants."
LJSpeech-1.1/wavs/LJ018-0086.wav|His demeanor immediately preceding his execution I have referred to in the last chapter.
LJSpeech-1.1/wavs/LJ044-0236.wav|it is unlikely that a reasoning person would plan to attempt to travel from Dallas, Texas to Cuba
LJSpeech-1.1/wavs/LJ028-0355.wav|he gave him likewise the government of Babylon for his life, free from tribute, and he also granted him many other favors.
LJSpeech-1.1/wavs/LJ031-0198.wav|Upon arrival, President Johnson made a brief statement over television and radio.
LJSpeech-1.1/wavs/LJ027-0105.wav|a number of organs which never could have been of use to any kind of creature save a terrestrial quadruped.
LJSpeech-1.1/wavs/LJ038-0238.wav|An examination of the window at the rear of the house, the wall through which the bullet passed, and the fence behind the house
LJSpeech-1.1/wavs/LJ014-0058.wav|These great criminals suffered at Horsemonger Lane Jail, but they were tried at the Central Criminal Court, and were for some time inmates of Newgate.
LJSpeech-1.1/wavs/LJ018-0303.wav|a second conspirator exchanged the gold for notes. But just as all promised well, the frauds were detected through the carelessness of the forgers.
LJSpeech-1.1/wavs/LJ030-0240.wav|to that effect immediately after the assassination.
LJSpeech-1.1/wavs/LJ003-0066.wav|As many various and, according to our ideas, heinous crimes came under this head,
LJSpeech-1.1/wavs/LJ015-0035.wav|produced immediate embarrassment and financial distress.
LJSpeech-1.1/wavs/LJ032-0230.wav|that the published pictures were the same as the original except for retouching done by these publications, apparently for the purpose of clarifying the lines of the rifle
LJSpeech-1.1/wavs/LJ007-0239.wav|both offenses and punishments affording a sufficient index to the practices going forward; and they wind up by declaring
LJSpeech-1.1/wavs/LJ002-0310.wav|that debtors who could afford the cabin and master's side were not permitted to share in the prison charities.
LJSpeech-1.1/wavs/LJ033-0036.wav|No curtain rods were known to have been discovered in the Depository Building after the assassination.
LJSpeech-1.1/wavs/LJ002-0235.wav|were places set apart for skittles, fives, and tennis, which strangers frequented as any other place of public amusement.
LJSpeech-1.1/wavs/LJ038-0295.wav|An official of this church told FBI agents that services are held every Wednesday at the church except during the month of August.
LJSpeech-1.1/wavs/LJ014-0045.wav|that Delarue had suffered by the hands of imaginary outraged brothers acting as the avengers of females deeply injured by him.
LJSpeech-1.1/wavs/LJ021-0036.wav|loans to the railroads and insurance companies and, finally, help for home owners and industry itself.
LJSpeech-1.1/wavs/LJ004-0039.wav|They were hopeless of any general reform by the action of the executive alone.
LJSpeech-1.1/wavs/LJ017-0011.wav|But secret poisoning on a wholesale scale such as was practiced in Italy and France was happily never popularized in England.
LJSpeech-1.1/wavs/LJ008-0037.wav|were brought out of Newgate about eight in the morning, and suspended on a gallows of a new construction.
LJSpeech-1.1/wavs/LJ027-0034.wav|Hence, as Jordan has said, "the inside of an animal tells the real history of its ancestry; the outside tells us only where its ancestors have been."
LJSpeech-1.1/wavs/LJ011-0066.wav|The concourse in front of Newgate was enormous, but much sympathy was evinced for this unfortunate victim to human weakness and ruthless laws.
LJSpeech-1.1/wavs/LJ046-0159.wav|accumulated over a twenty-year period, some of which included more than one individual.
LJSpeech-1.1/wavs/LJ027-0079.wav|a series of either fore or hind limbs of a mammal with one toe (horse),
LJSpeech-1.1/wavs/LJ019-0247.wav|which existed in the various prisons,
LJSpeech-1.1/wavs/LJ034-0059.wav|Since other identifiable prints were developed on the cartons, the Commission requested that they be compared with the prints of the twelve warehouse employees
LJSpeech-1.1/wavs/LJ001-0106.wav|oddity rather than rational beauty and meaning being apparently the thing sought for both in the letters and the illustrations.
LJSpeech-1.1/wavs/LJ019-0158.wav|Later on a more efficacious but still imperfect method of supervision was introduced. Iron cages, which are still to be seen in Newgate,
LJSpeech-1.1/wavs/LJ040-0079.wav|John Pic testified that he thought Lee found in Ekdahl the father that he never had.
LJSpeech-1.1/wavs/LJ019-0309.wav|The main object of this act was to compass that uniformity in discipline and treatment generally
LJSpeech-1.1/wavs/LJ017-0271.wav|Lyons asked the time, and was told it was only five.
LJSpeech-1.1/wavs/LJ037-0015.wav|but he saw the policeman leave the car, heard three or four shots, and then saw the policeman fall.
LJSpeech-1.1/wavs/LJ029-0109.wav|Representatives of the local host committee and the White House staff were advised by the Secret Service of the actual route on the afternoon of November eighteen.
LJSpeech-1.1/wavs/LJ021-0006.wav|have had to do with industry and labor and with respect to these, certain developments have taken place which I consider of importance.
LJSpeech-1.1/wavs/LJ039-0065.wav|so that the President would have been moving in an almost straight line away from the assassin's rifle.
LJSpeech-1.1/wavs/LJ011-0144.wav|but Mr. Joseph Hume pressed the Government hard, and obtained an assurance that the men should not be executed.
LJSpeech-1.1/wavs/LJ014-0246.wav|Thus, when a payment was made by the company, the amount disbursed was carried to account in the general books from its entry in the passbook,
LJSpeech-1.1/wavs/LJ007-0124.wav|The infirmary at this particular period epitomized the condition of the jail at large.
LJSpeech-1.1/wavs/LJ030-0013.wav|David F. Powers of the President's staff later stated that when the President asked for his assessment of the day's activities, Powers replied
LJSpeech-1.1/wavs/LJ038-0224.wav|Another statement which limits the time when it could have been written is the reference, quote, you and the baby, end quote,
LJSpeech-1.1/wavs/LJ033-0213.wav|(three) removed the rifle from the blanket in the Paines' garage on Thursday evening;
LJSpeech-1.1/wavs/LJ017-0051.wav|covered rather scantily with light sandy hair.
LJSpeech-1.1/wavs/LJ039-0202.wav|At fifteen yards each man's shots landed within the size of a dime.
LJSpeech-1.1/wavs/LJ016-0245.wav|Until the time of his death he kept a small shop close to the church in Horncastle.
LJSpeech-1.1/wavs/LJ026-0145.wav|In the animal carbon dioxide, water and nitrogen compounds are the chief excretions.
LJSpeech-1.1/wavs/LJ016-0087.wav|Among the escapes still remembered was one in eighteen forty-nine, accomplished by a man who had been employed
LJSpeech-1.1/wavs/LJ001-0049.wav|After his death in the "fourteen eighties," or at least by fourteen ninety, printing in Venice had declined very much;
LJSpeech-1.1/wavs/LJ016-0349.wav|that of Alexander Mackay, who murdered his mistress at Norton Folgate by beating her with a rolling-pin and furnace-rake,
LJSpeech-1.1/wavs/LJ009-0070.wav|The youth's hands tremble as they hold the book upside down.
LJSpeech-1.1/wavs/LJ047-0079.wav|The New Orleans office investigated and located Oswald, learning his address and former place of employment on August five, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ012-0185.wav|raised the alarm, and suspicion fell upon the three murderers, who were arrested.
LJSpeech-1.1/wavs/LJ015-0102.wav|He came back to explain that he had mislaid them.
LJSpeech-1.1/wavs/LJ046-0110.wav|is the identification and elimination of possible sources of danger to the President before the danger becomes actual.
LJSpeech-1.1/wavs/LJ012-0205.wav|an avowed "snatcher" and habitué of the Fortune of War, a public-house in Smithfield frequented openly by men of this awful profession.
LJSpeech-1.1/wavs/LJ048-0035.wav|It was against this background and consistent with the criteria followed by the FBI prior to November twenty-two
LJSpeech-1.1/wavs/LJ017-0260.wav|Vartos the Turk, and Carlos the Greek.
LJSpeech-1.1/wavs/LJ029-0204.wav|Two days later, a local Republican leader called for a "civilized nonpartisan" welcome
LJSpeech-1.1/wavs/LJ010-0264.wav|Later on, however, Dasset was himself seized and interrogated,
LJSpeech-1.1/wavs/LJ038-0037.wav|Oswald then struck McDonald between the eyes with his left fist; with his right hand he drew a gun from his waist.
LJSpeech-1.1/wavs/LJ035-0137.wav|About this time Shelley saw Truly and Patrolman Baker go into the building
LJSpeech-1.1/wavs/LJ016-0344.wav|The ceremony, which was witnessed by only a few officials and representatives of the press, was performed with the utmost decency and decorum.
LJSpeech-1.1/wavs/LJ014-0229.wav|Mobbs systematically ill-used his wife for a long space of time, and at last cut her throat.
LJSpeech-1.1/wavs/LJ022-0087.wav|After the Division of Applications and Information has sifted those projects,
LJSpeech-1.1/wavs/LJ004-0047.wav|One of the moving spirits was the Honorable H. G. Bennet, M.P., whose vigorous protests against the lamentable condition of Newgate have already been recorded.
LJSpeech-1.1/wavs/LJ048-0147.wav|The Commission believes
LJSpeech-1.1/wavs/LJ027-0073.wav|may be shown to be modifications one of another.
LJSpeech-1.1/wavs/LJ030-0082.wav|The agents on the front of the running boards had directions to move immediately to positions just to the rear of the President and Mrs. Kennedy when the President's car slowed
LJSpeech-1.1/wavs/LJ036-0134.wav|I asked him where he wanted to go. And he said, "five hundred North Beckley. Well, I started up,
LJSpeech-1.1/wavs/LJ008-0295.wav|When the council had decided, the news was conveyed to Newgate by the Recorder, who made his "report," as it was called.
LJSpeech-1.1/wavs/LJ038-0153.wav|He said that he left work because Bill Shelley said that there would be no more work done that day in the building.
LJSpeech-1.1/wavs/LJ012-0126.wav|The next year twelve thousand sovereigns were cleverly stolen in the Mile End Road.
LJSpeech-1.1/wavs/LJ012-0087.wav|should be introduced into the building, and secreted there during the night to accomplish the robbery.
LJSpeech-1.1/wavs/LJ008-0141.wav|the doubtfulness of the issue, or the superior position of the perpetrator,
LJSpeech-1.1/wavs/LJ018-0100.wav|took to appropriating the bills intrusted to him, and so lost his business, after which he became a clerk to Messrs. Wagner and Bateman.
LJSpeech-1.1/wavs/LJ012-0237.wav|A very painful scene occurred in Newgate when the news of his escape from death was imparted to May.
LJSpeech-1.1/wavs/LJ031-0168.wav|In another car Mrs. Johnson was driven to the airport accompanied by Secret Service agents and Representative Brooks.
LJSpeech-1.1/wavs/LJ048-0087.wav|The President's trip to Dallas called into play many standard operating procedures of the Secret Service in addition to its preventive intelligence operations.
LJSpeech-1.1/wavs/LJ040-0174.wav|Lee confirmed some of those observations by saying that he felt almost as if there were a veil between him and other people
LJSpeech-1.1/wavs/LJ031-0166.wav|Unmarked police cars took the Vice President and Mrs. Johnson from Parkland Hospital to Love Field.
LJSpeech-1.1/wavs/LJ014-0301.wav|In eighteen fifty-three a second case of gigantic fraud alarmed and scandalized the financial world.
LJSpeech-1.1/wavs/LJ019-0086.wav|or they might herd together or communicate freely as in the old worst days. They might see each other when they liked, and converse sotto voce,
LJSpeech-1.1/wavs/LJ039-0074.wav|you should not have any difficulty in hitting your target. I mean it requires no training at all to shoot a weapon with a telescopic sight
LJSpeech-1.1/wavs/LJ001-0087.wav|for the seventeenth-century letters are at least pure and simple in line. The Italian, Bodoni, and the Frenchman, Didot,
LJSpeech-1.1/wavs/LJ004-0054.wav|In order to give greater value to the pamphlet,
LJSpeech-1.1/wavs/LJ010-0186.wav|There is no occasion to use violence. I will go with you.
LJSpeech-1.1/wavs/LJ011-0135.wav|Macintosh's amendment was carried in the Commons, but the new law did not pass the Lords, who re-enacted the capital penalty.
LJSpeech-1.1/wavs/LJ040-0092.wav|when he left school in order to get into the Coast Guard. Since his mother did not approve of his decision to continue school
LJSpeech-1.1/wavs/LJ010-0285.wav|invariably went out in a cab, for which he always paid the same fare,
LJSpeech-1.1/wavs/LJ012-0209.wav|and after some haggling they agreed on a price, and in the afternoon the snatchers brought a hamper which contained a body in a sack.
LJSpeech-1.1/wavs/LJ016-0327.wav|declared that they were not prepared to agree to the resolution respecting private executions.
LJSpeech-1.1/wavs/LJ028-0477.wav|To protect the sun-dried bricks of the inner wall from the winter rains
LJSpeech-1.1/wavs/LJ025-0173.wav|The watery solution, in which its roots are plunged, contains nitrogen but no carbon;
LJSpeech-1.1/wavs/LJ048-0279.wav|They work long, hard hours, under very great strain, and must travel frequently.
LJSpeech-1.1/wavs/LJ019-0331.wav|Baths were provided, ablutions ordered, and all appliances to insure personal cleanliness.
LJSpeech-1.1/wavs/LJ019-0300.wav|The committee might well suggest the abolition of these jails, or their amalgamation with the larger county establishments in their immediate neighborhood.
LJSpeech-1.1/wavs/LJ031-0092.wav|Did you ever have occasion to look at the President's back?
LJSpeech-1.1/wavs/LJ014-0131.wav|but Mrs. Manning, speaking in a foreign accent, addressed the court with great fluency and vehemence.
LJSpeech-1.1/wavs/LJ016-0009.wav|He had friends and auxiliaries inside the jail and out. The cell he occupied was near the outer wall,
LJSpeech-1.1/wavs/LJ039-0181.wav|the shots would have been evenly spaced and the assassin would not have incurred so sharp an angular movement.
LJSpeech-1.1/wavs/LJ013-0202.wav|Coolness amounting almost to effrontery gave way to hopeless dejection.
LJSpeech-1.1/wavs/LJ003-0234.wav|The bedding was scanty; fuel and light had to be purchased out of prisoners' private means; clothing was issued but rarely,
LJSpeech-1.1/wavs/LJ004-0014.wav|filthiness, severity, or neglect; many new dungeons had aggravated the evils against which his sagacity could not but remonstrate;
LJSpeech-1.1/wavs/LJ018-0188.wav|Presently "Old Bob" drove up to Camberwell Gate in the same cart in which he had been seen to start.
LJSpeech-1.1/wavs/LJ002-0028.wav|In order to realize the evils entailed by incarceration in Newgate in these days, it is necessary to give some account of its interior
LJSpeech-1.1/wavs/LJ033-0029.wav|It would appear, however, that obtaining curtain rods was not the purpose of Oswald's trip to Irving on November twenty-one.
LJSpeech-1.1/wavs/LJ039-0067.wav|which is ordinarily required when a marksman must raise his rifle as a target moves farther away.
LJSpeech-1.1/wavs/LJ038-0105.wav|They discovered two photographs, each showing Oswald with a rifle and a pistol.
LJSpeech-1.1/wavs/LJ040-0049.wav|He stated several times that he was a Communist but apparently never joined any Communist Party.
LJSpeech-1.1/wavs/LJ015-0030.wav|The bank had been conducted on false principles;
LJSpeech-1.1/wavs/LJ039-0172.wav|None of the marksmen had any practice with the assassination weapon except for exercising the bolt for two or three minutes on a dry run.
LJSpeech-1.1/wavs/LJ029-0088.wav|securing the roof and insuring the presence of numerous police officers inside and around the building.
LJSpeech-1.1/wavs/LJ009-0235.wav|and having first pulled him sideways, then got upon his shoulders, so that the rope broke.
LJSpeech-1.1/wavs/LJ013-0180.wav|The intention of the real murderer to shift the crime to burglars was evident although futile,
LJSpeech-1.1/wavs/LJ019-0215.wav|Why not move the city prison bodily into this more rural spot, with its purer air and greater breathing space?
LJSpeech-1.1/wavs/LJ009-0136.wav|that they reluctantly agreed to open the gallery which had formerly been occupied by strangers on these occasions.
LJSpeech-1.1/wavs/LJ034-0052.wav|In his independent investigation, Arthur Mandella of the New York City Police Department
LJSpeech-1.1/wavs/LJ007-0055.wav|The more peaceably disposed found some occupation in making Newgate tokens,
LJSpeech-1.1/wavs/LJ003-0018.wav|and discipline maintained by a system open to grave abuses, and which had the prescription of long usage,
LJSpeech-1.1/wavs/LJ028-0482.wav|but I, the devout petitioner, the worshipper of the gods, built the moat, and made its wall of burned brick and bitumen mountain high.
LJSpeech-1.1/wavs/LJ032-0123.wav|the rifle was released to the FBI and forwarded to Washington where it was examined on the morning of November twenty-three
LJSpeech-1.1/wavs/LJ043-0102.wav|It is possible that his immediate supervisor noticed the newspaper at that time because his attention had otherwise been drawn more directly to Oswald.
LJSpeech-1.1/wavs/LJ002-0212.wav|Mexico, and was consumed at the rate of a hogshead per week.
LJSpeech-1.1/wavs/LJ003-0039.wav|Giltspur Street, and the Poultry, or about four hundred and seventy-six in all.
LJSpeech-1.1/wavs/LJ047-0065.wav|This information led Hosty to review Oswald's file, from which he learned that Oswald had become a subscriber to the Worker,
LJSpeech-1.1/wavs/LJ032-0264.wav|tied with a string, lying on the floor of the Paines' garage.
LJSpeech-1.1/wavs/LJ005-0291.wav|In some large towns, as at Berwick on Tweed, Southampton, and Southwark, they (the prisons) are in a very discreditable condition.
LJSpeech-1.1/wavs/LJ007-0132.wav|The inspectors, however, honestly admitted that although the site of the prison was convenient, its construction was as bad as bad could be.
LJSpeech-1.1/wavs/LJ010-0067.wav|This Thistlewood had seen many vicissitudes throughout his strange, adventurous career. The son of a respectable Lincolnshire farmer,
LJSpeech-1.1/wavs/LJ004-0147.wav|The irons, which nearly every one wore, were remarkably heavy; those double ironed could not take off their small clothes.
LJSpeech-1.1/wavs/LJ028-0128.wav|His brief description of them should not be omitted. He says that Nebuchadnezzar
LJSpeech-1.1/wavs/LJ048-0019.wav|His activities for the Fair Play for Cuba Committee in New Orleans, we knew, were not of real consequence as he was not connected with any organized activity there.
LJSpeech-1.1/wavs/LJ025-0047.wav|The plant withdraws water and carbonic acid from the atmosphere, the animal contributes both to it.
LJSpeech-1.1/wavs/LJ031-0027.wav|Upon arriving at Parkland Hospital,
LJSpeech-1.1/wavs/LJ039-0167.wav|Using the assassination rifle mounted with the telescopic sight, three marksmen, rated as master by the National Rifle Association,
LJSpeech-1.1/wavs/LJ035-0117.wav|Harold Norman, and Bonnie Ray Williams -- were watching the parade from the fifth floor, directly below the window from which the shots were fired.
LJSpeech-1.1/wavs/LJ037-0201.wav|Heinz W. Michaelis, office manager of both George Rose and Co., Incorporated and Seaport Traders, Incorporated.
LJSpeech-1.1/wavs/LJ006-0203.wav|and he had thus ample means of introducing to the prisoners the prohibited but always much-coveted and generally procurable weed.
LJSpeech-1.1/wavs/LJ007-0209.wav|they return to the charge, and again call the corporation to task for their mismanagement of Newgate.
LJSpeech-1.1/wavs/LJ019-0084.wav|The greatest pains might be taken to secure isolation,
LJSpeech-1.1/wavs/LJ009-0138.wav|all the avenues to the prison gates were blocked by ticket-holders.
LJSpeech-1.1/wavs/LJ039-0215.wav|Frazier added that the scope would cause a slight miss to the right.
LJSpeech-1.1/wavs/LJ018-0172.wav|More than this, Griffiths took the police to a field where, in a bank, a number of other plates were secreted.
LJSpeech-1.1/wavs/LJ030-0091.wav|Rufus W. Youngblood, special agent in charge of the Vice President's detail,
LJSpeech-1.1/wavs/LJ037-0046.wav|The man, quote, in kind of a little trot, end quote, headed down Patton toward Jefferson Boulevard, a block away.
LJSpeech-1.1/wavs/LJ046-0223.wav|to Secret Service locally, end quote.
LJSpeech-1.1/wavs/LJ049-0175.wav|before the President reached Dallas.
LJSpeech-1.1/wavs/LJ021-0106.wav|the representatives of trade and industry were permitted to write their ideas into the codes.
LJSpeech-1.1/wavs/LJ009-0021.wav|in which it was said I had enlarged upon the heinous nature of his crime, and warned the public to avoid such conduct.
LJSpeech-1.1/wavs/LJ016-0343.wav|The sufferer was a porter on the London, Chatham, and Dover railway, sentenced to death for shooting the station-master at Dover.
LJSpeech-1.1/wavs/LJ030-0128.wav|From Main Street the motorcade turned right and went north on Houston Street, passing tall buildings on the right,
LJSpeech-1.1/wavs/LJ022-0003.wav|Since my annual message to the Congress on January fourth, last, I have not addressed the general public over the air.
LJSpeech-1.1/wavs/LJ016-0275.wav|As much as twenty-five pounds was paid for a first-floor front on this occasion.
LJSpeech-1.1/wavs/LJ002-0136.wav|and the disuse of the inferior courts.
LJSpeech-1.1/wavs/LJ018-0253.wav|For these crimes William Roupell was tried at the Central Criminal Court on the twenty-fourth September, eighteen sixty-two.
LJSpeech-1.1/wavs/LJ012-0200.wav|Bishop got weary of the dangers and fatigues of exhumation, and proposed to Williams that instead of disinterring they should murder their subjects.
LJSpeech-1.1/wavs/LJ008-0005.wav|The terrible spectacle was as demoralizing to the public, for whose admonition it was intended,
LJSpeech-1.1/wavs/LJ049-0096.wav|There have been a number of efforts to make assassination a Federal crime, particularly after the assassination of President McKinley
LJSpeech-1.1/wavs/LJ028-0148.wav|Then they set to building, and began by bricking the borders of the moat, after which they proceeded to construct the wall itself,
LJSpeech-1.1/wavs/LJ047-0218.wav|had discussed the President's visit on several occasions, including the regular biweekly conference on the morning of November twenty-two
LJSpeech-1.1/wavs/LJ005-0299.wav|The whole question was again dealt with in Lord John Russell's bill for the reform of the municipal corporations, and with a more liberal election of town councilors,
LJSpeech-1.1/wavs/LJ017-0250.wav|from Peru bound to Bordeaux, which had foundered at sea;
LJSpeech-1.1/wavs/LJ004-0062.wav|and the reason is plain: you have taken him from his home, and have deprived him of the means of providing himself with the necessaries or comforts of life,
LJSpeech-1.1/wavs/LJ013-0112.wav|Within a month or two the bank of Messrs. Rogers and Co., Clement's Lane, was broken into.
LJSpeech-1.1/wavs/LJ042-0110.wav|stated that Mrs. Oswald told her everybody in Russia, quote, hated him, end quote.
LJSpeech-1.1/wavs/LJ047-0210.wav|I think all of those, if we had them all together,
LJSpeech-1.1/wavs/LJ003-0210.wav|at night they were placed in the fifteen cells, two, three, or more together, according to the total number to be accommodated.
LJSpeech-1.1/wavs/LJ048-0083.wav|were discussed twice officially by the special agent in charge of the FBI office in Dallas. As discussed in chapter two,
LJSpeech-1.1/wavs/LJ002-0156.wav|Thomas Dobson, on twenty-second August, seventeen ninety-nine, for one shilling, with costs of eight shillings, ten pence.
LJSpeech-1.1/wavs/LJ028-0179.wav|It is only from their ruins that we may hope to obtain accurate information of the strongest fortifications in the ancient world.
LJSpeech-1.1/wavs/LJ037-0122.wav|The Dallas Police Department furnished the Commission with pictures of the men who appeared in the lineups with Oswald,
LJSpeech-1.1/wavs/LJ014-0055.wav|Next year John Gleeson Wilson, at Liverpool, murdered a woman, Ann Henrichson, also a maidservant and two children;
LJSpeech-1.1/wavs/LJ049-0028.wav|The Secret Service has therefore suggested this practice only on extraordinary occasions.
LJSpeech-1.1/wavs/LJ001-0020.wav|the "lower-case" being in fact invented in the early Middle Ages.
LJSpeech-1.1/wavs/LJ003-0333.wav|But here the recommendations touched at once upon the delicate subject of expense, and it is clear that the committee hesitated on this score.
LJSpeech-1.1/wavs/LJ038-0216.wav|The references to house rent and payments for water and gas
LJSpeech-1.1/wavs/LJ008-0287.wav|to make those sanctions an object of contemptuous mockery.
LJSpeech-1.1/wavs/LJ035-0003.wav|In considering whether Oswald was at the southeast corner window at the time the shots were fired,
LJSpeech-1.1/wavs/LJ028-0069.wav|how he cast Hebrew lads into a fiery furnace and into the lions' den,
LJSpeech-1.1/wavs/LJ043-0005.wav|Apart from his relatives, Oswald had no friends or close associates in Texas when he returned there in June of nineteen sixty-two,
LJSpeech-1.1/wavs/LJ016-0315.wav|Colonel (now Sir Edmund) Henderson was strongly in favor of them,
LJSpeech-1.1/wavs/LJ013-0152.wav|at Montreuil. He was arraigned at the Old Bailey, and the case fully proved. His sentence was seven years' transportation.
LJSpeech-1.1/wavs/LJ015-0090.wav|To account for his revenues he pretended to have been very lucky on the Stock Exchange, which was at one time true to a limited extent,
LJSpeech-1.1/wavs/LJ028-0185.wav|Perhaps Babylon was so strongly fortified that at first he made no attempt to add it to his empire,
LJSpeech-1.1/wavs/LJ014-0086.wav|This job was not completed till the following day, as the hole had to be enlarged, and the only tool they had was a dust-shovel.
LJSpeech-1.1/wavs/LJ018-0272.wav|Mrs. Tarpey was almost immediately captured and put on her trial, but she was acquitted on the plea that she had acted under the coercion of her husband.
LJSpeech-1.1/wavs/LJ004-0177.wav|No prison dress was allowed; no reception-room was provided, no soap, towels, or baths.
LJSpeech-1.1/wavs/LJ002-0079.wav|Its name and its situation were the same as those of the old place of carrying out the terrible sentence inflicted on accused persons who stood mute.
LJSpeech-1.1/wavs/LJ039-0231.wav|Having fired this slot
LJSpeech-1.1/wavs/LJ041-0106.wav|At the court-martial hearing which followed, Oswald admitted that he had been rather drunk when the incident occurred.
LJSpeech-1.1/wavs/LJ008-0305.wav|they never ceased cursing until the passion of anger so excited was exchanged for joy in some and grief in others.
LJSpeech-1.1/wavs/LJ046-0081.wav|The men in charge of protecting the President, confronted by complex problems and limited as they are in the measures they may employ,
LJSpeech-1.1/wavs/LJ003-0330.wav|The state side ceased to exist, and the female prisoners thus regained the space of which their quadrangle had been robbed.
LJSpeech-1.1/wavs/LJ022-0004.wav|In the many weeks since that time the Congress has devoted itself to the arduous task of formulating legislation necessary to the country's welfare.
LJSpeech-1.1/wavs/LJ017-0110.wav|He said nothing, but began to feel uneasy when he found that Cook's betting-book was missing, and that Palmer put it forward
LJSpeech-1.1/wavs/LJ014-0288.wav|That same evening he committed suicide in Newgate.
LJSpeech-1.1/wavs/LJ047-0245.wav|His secretary testified that she prepared such a report for him that afternoon and Chief of Police Jesse E. Curry
LJSpeech-1.1/wavs/LJ045-0200.wav|that over the weekend he did think about his wife's request that he not come to Irving, which was prompted by the birthday party being held at the Paine home.
LJSpeech-1.1/wavs/LJ025-0055.wav|by the employment of instruments of precision for the measurement of the physical forces which are at work in the living economy.
LJSpeech-1.1/wavs/LJ013-0222.wav|he did not shrink from murder, both for revenge and to conceal his other crimes.
LJSpeech-1.1/wavs/LJ050-0242.wav|even though it agrees with the Secret Service that it is preferable for the Service to have enough agents to handle all protective demands.
LJSpeech-1.1/wavs/LJ036-0046.wav|She testified, quote, I didn't like his attitude. There was just something about him I didn't like or want him. Just didn't want him around me, end quote,
LJSpeech-1.1/wavs/LJ014-0221.wav|On the contrary, many of them encouraged the brutal assailant in his savage attack.
LJSpeech-1.1/wavs/LJ045-0244.wav|Long before the assassination he expressed his hatred for American society and acted in protest against it.
LJSpeech-1.1/wavs/LJ010-0090.wav|Hand-grenades were to be thrown into the dining-room, and during the noise and confusion the assassination of the ministers was to be completed,
LJSpeech-1.1/wavs/LJ033-0199.wav|because other types of fibers present in the blanket were not found in the bag.
LJSpeech-1.1/wavs/LJ009-0141.wav|Lord Paget, Lord Bruce, several members of the House of Commons, and a few ladies.
LJSpeech-1.1/wavs/LJ010-0071.wav|It was during this period that he was said to have imbibed his revolutionary ideas.
LJSpeech-1.1/wavs/LJ027-0170.wav|Finally, it loses the tail, or rather its tail is absorbed and its material used in further development, and it becomes a perfect frog,
LJSpeech-1.1/wavs/LJ046-0049.wav|More often than not, Presidential journeys have served more than one purpose at the same time: ceremonial,
LJSpeech-1.1/wavs/LJ021-0045.wav|They saw that without changes in the policies and methods of investment
LJSpeech-1.1/wavs/LJ039-0145.wav|According to George De Mohrenschildt, Oswald said that he went target shooting with that rifle.
LJSpeech-1.1/wavs/LJ019-0392.wav|in the administration of prisons.
LJSpeech-1.1/wavs/LJ032-0067.wav|Postal Inspector Harry D. Holmes of the Dallas Post Office testified, however, that when a package is received for a certain box,
LJSpeech-1.1/wavs/LJ008-0249.wav|Blinded with their long hair, they tore at each other like two furies; their bonnets and caps were trodden underfoot in the kennel,
LJSpeech-1.1/wavs/LJ026-0019.wav|they cannot ingest solid food, but are nourished by a watery solution of nutrient materials.
LJSpeech-1.1/wavs/LJ011-0218.wav|spoke severely of the gross deception practiced upon an innocent girl, and sentenced the brothers each to three years' imprisonment,
LJSpeech-1.1/wavs/LJ021-0072.wav|Also, billions of dollars of invested capital have today a greater security of present and future earning power than before.
LJSpeech-1.1/wavs/LJ006-0174.wav|The aldermen never called upon him to report, and left him nearly unsupervised and uncontrolled.
LJSpeech-1.1/wavs/LJ044-0223.wav|whether or not he agreed with Castro that President Kennedy was a, quote, ruffian and a thief, end quote. He replied that he, quote,
LJSpeech-1.1/wavs/LJ045-0010.wav|The Commission has found no evidence that the extreme views expressed toward President Kennedy
LJSpeech-1.1/wavs/LJ040-0041.wav|There was some quality about him that led him to act with an apparent disregard for possible consequences.
LJSpeech-1.1/wavs/LJ032-0174.wav|but Mary Bledsoe, a former landlady of Oswald, saw him on a bus approximately ten minutes after the assassination
LJSpeech-1.1/wavs/LJ013-0223.wav|Courvoisier wished to commit suicide in Newgate, but was prevented by the vigilant supervision to which he was subjected while in jail.
LJSpeech-1.1/wavs/LJ023-0014.wav|In effect, four Justices ruled that the right under a private contract
LJSpeech-1.1/wavs/LJ050-0127.wav|should negotiate similar arrangements with such other State and local law enforcement agencies as may provide meaningful assistance.
LJSpeech-1.1/wavs/LJ019-0139.wav|These numbers would have still further decreased, and the jail would have been almost empty, but for the misdemeanants who were still sent to Newgate
LJSpeech-1.1/wavs/LJ022-0049.wav|The simple fact is that many million more people have private work today than two years ago today or one year ago today,
LJSpeech-1.1/wavs/LJ013-0246.wav|Some time elapsed before the imprisoned party could force open the doors, and by then the fugitive had escaped.
LJSpeech-1.1/wavs/LJ025-0095.wav|once supposed to be exclusively confined to plants, are now known to be regular and normal products of animals.
LJSpeech-1.1/wavs/LJ022-0033.wav|"To get away from the trees", as they say, "and to look at the whole forest."
LJSpeech-1.1/wavs/LJ038-0305.wav|The finding that Lee Harvey Oswald attempted to murder a public figure in April nineteen sixty-three
LJSpeech-1.1/wavs/LJ027-0101.wav|Throughout both the animal and vegetable kingdoms dwarfed and useless representatives of organs are constantly met with,
LJSpeech-1.1/wavs/LJ022-0054.wav|The first is to make provisions intended to relieve, to minimize, and to prevent future unemployment;
LJSpeech-1.1/wavs/LJ012-0110.wav|The police lost all trace of them for some days, but at length Sullivan's brother was followed from the house in Kennington to the above-mentioned tavern.
LJSpeech-1.1/wavs/LJ038-0158.wav|Jarman testified that he ate his lunch on the first floor around five minutes to twelve, and that he neither ate lunch with nor saw Oswald.
LJSpeech-1.1/wavs/LJ027-0061.wav|in order to enclose and protect a similar enlargement of the nervous center,
LJSpeech-1.1/wavs/LJ042-0092.wav|No evidence has been found that they used him for any particular propaganda or other political or informational purposes.
LJSpeech-1.1/wavs/LJ017-0141.wav|could not divest his mind of serious doubt, and of which the murderer got the benefit.
LJSpeech-1.1/wavs/LJ032-0181.wav|Although Stombaugh was unable to estimate the period of time the fibers were on the rifle he said that the fibers, quote,
LJSpeech-1.1/wavs/LJ008-0076.wav|When she came out of prison she appeared languid and terrified, and trembled greatly as she advanced to the stake,
LJSpeech-1.1/wavs/LJ029-0205.wav|for President Kennedy, stating that "in many respects Dallas County has isolated itself from the main stream of life in the world in this decade.
LJSpeech-1.1/wavs/LJ014-0126.wav|her face was comely, she had dark hair and good eyes, and was above the middle height, yet inclined to be stout.
LJSpeech-1.1/wavs/LJ025-0087.wav|On the other hand, the definition thus amended will exclude all ordinary vegetable organisms.
LJSpeech-1.1/wavs/LJ028-0158.wav|The city wall is brought down on both sides to the edge of the stream,
LJSpeech-1.1/wavs/LJ019-0064.wav|that their condition was more natural, and approximated more nearly to that of daily life.
LJSpeech-1.1/wavs/LJ001-0036.wav|But about the same year Mentelin at Strasburg began to print in a type which is distinctly Roman;
LJSpeech-1.1/wavs/LJ018-0153.wav|the officers ensconced themselves in the latter, and waited for Buncher's expected visit.
LJSpeech-1.1/wavs/LJ049-0150.wav|A Cabinet-level committee which is actively concerned with these problems would be able to discuss these matters more effectively with the President.
LJSpeech-1.1/wavs/LJ018-0389.wav|Of the lesser criminals, forgers, thieves, swindlers, Newgate continued to receive its full share up to the last.
LJSpeech-1.1/wavs/LJ021-0121.wav|But I would point out that the extent and severity of labor disputes during this period
LJSpeech-1.1/wavs/LJ046-0241.wav|PRS required a more direct indication of a threat to the President, and that there was no such indication until the President's scheduled visit to that area became known.
LJSpeech-1.1/wavs/LJ009-0009.wav|This rule has some, but very few, exceptions; such as where a hardened offender behaves with great levity and brutality, as if he cared nought for his life,
LJSpeech-1.1/wavs/LJ011-0256.wav|By this time the neighbors were aroused, and several people came to the scene of the affray.
LJSpeech-1.1/wavs/LJ020-0098.wav|Having made out your rolls and tucked them up snugly for the final rise, return to your chamber for a comfortable bath and toilet.
LJSpeech-1.1/wavs/LJ018-0223.wav|In eighteen fifty-six the father died.
LJSpeech-1.1/wavs/LJ028-0045.wav|When Esarhaddon died, one of his sons, Samas-sum-yukin, was made King of Babylon.
LJSpeech-1.1/wavs/LJ019-0242.wav|Newgate naturally shared in any advantages due to these reforms. I propose, therefore, to refer to them in the concluding pages of this work,
LJSpeech-1.1/wavs/LJ022-0185.wav|The answer to this demand was the Federal Reserve System.
LJSpeech-1.1/wavs/LJ024-0104.wav|I am therefore, going to spend my time, my efforts and my money
LJSpeech-1.1/wavs/LJ028-0276.wav|a marvelous thing happened to Zopyrus, son of the Megabyzus who was among the seven men that overthrew the Magus.
LJSpeech-1.1/wavs/LJ013-0140.wav|A robbery of a somewhat novel kind was executed in rather a bungling fashion by Ker, a sea-captain,
LJSpeech-1.1/wavs/LJ028-0372.wav|The poor of the surrounding country occupied its dismantled palaces.
LJSpeech-1.1/wavs/LJ025-0076.wav|Many animals of even complex structure which live parasitically within others are wholly devoid of an alimentary cavity.
LJSpeech-1.1/wavs/LJ016-0120.wav|This was considered safer than intrusting him with keys.
LJSpeech-1.1/wavs/LJ015-0285.wav|and when these presented themselves, entrusted them as a beginning with the duty of cashing cheques.
LJSpeech-1.1/wavs/LJ046-0201.wav|were no more specific than the broad and general instructions its own agents and the White House mailroom.
LJSpeech-1.1/wavs/LJ030-0109.wav|The Vice-Presidential car
LJSpeech-1.1/wavs/LJ009-0093.wav|Why does no one stir to help him? Where would be the use? The hardened burglar moves not, nor does he speak;
LJSpeech-1.1/wavs/LJ013-0194.wav|but on the second day the discovery of fresh evidence, more particularly the recovery of some of Lord William's stolen plate,
LJSpeech-1.1/wavs/LJ001-0065.wav|This was notably the case with the early works printed at Ulm, and in a somewhat lesser degree at Augsburg.
LJSpeech-1.1/wavs/LJ034-0171.wav|Edwards said, quote, Look at that guy there in that window, end quote,
LJSpeech-1.1/wavs/LJ040-0107.wav|but apparently was not able to spend as much time with them as he would have liked, because of the age gaps of five and seven years,
LJSpeech-1.1/wavs/LJ017-0280.wav|The convicts were pinioned one by one and sent singly out to the gallows.
LJSpeech-1.1/wavs/LJ028-0079.wav|The museum authorities believed that the cameo was one of the many spurious objects which the Eastern forgers were constantly sending to Europe,
LJSpeech-1.1/wavs/LJ022-0066.wav|will not only help to guard the individual in future periods of lay-off against dependence upon relief,
LJSpeech-1.1/wavs/LJ012-0095.wav|The jewels had belonged to a Spanish countess recently deceased, who had sent them to England for greater security on the outbreak of the first Carlist war.
LJSpeech-1.1/wavs/LJ024-0035.wav|Let me answer this question with a bluntness that will end all honest misunderstanding of my purposes.
LJSpeech-1.1/wavs/LJ007-0163.wav|all the tumultuous and diversified passions and emotions which circumstances like these must necessarily generate
LJSpeech-1.1/wavs/LJ034-0021.wav|Sebastian F. Latona, supervisor of the Latent Fingerprint Section,
LJSpeech-1.1/wavs/LJ008-0284.wav|Nothing could be more strongly marked than the contrast between the ultimate destiny of different individuals all abiding the same awful doom:
LJSpeech-1.1/wavs/LJ041-0138.wav|and that she could not think of any reason why Oswald would want to kill President Kennedy.
LJSpeech-1.1/wavs/LJ017-0043.wav|The direful suspicions which surrounded the case filled the whole country with uneasiness and misgiving,
LJSpeech-1.1/wavs/LJ008-0219.wav|their conversation was of companions and associates of former years, long ago imprisoned, transported, hanged, while they,
LJSpeech-1.1/wavs/LJ030-0120.wav|had to leave the left front running board of the President's follow-up car four times to ride on the rear of the President's limousine.
LJSpeech-1.1/wavs/LJ037-0165.wav|with five lands and grooves and a right twist which were the rifling characteristics of the revolver taken from Oswald.
LJSpeech-1.1/wavs/LJ012-0020.wav|He began as an itinerant street vendor at eight, at ten he passed bad money,
LJSpeech-1.1/wavs/LJ016-0337.wav|In the houses opposite the prison numbers of detectives mixed with the spectators;
LJSpeech-1.1/wavs/LJ050-0011.wav|The Chief of the Service now reports to the Secretary of the Treasury
LJSpeech-1.1/wavs/LJ035-0016.wav|He saw pigeons flutter upward. He was not certain, quote, but I am pretty sure they came from the building right on the northwest corner, end quote.
LJSpeech-1.1/wavs/LJ018-0364.wav|It will be remembered that she made a statement which led to the empaneling of a jury of matrons, who decided that there was no cause for an arrest of judgment.
LJSpeech-1.1/wavs/LJ006-0073.wav|of his many manifest duties, but I shall here confine myself to animadverting on his neglect as regards the appropriation of his prison.
LJSpeech-1.1/wavs/LJ026-0130.wav|and may thus be easily transported to all parts of the plant.
LJSpeech-1.1/wavs/LJ017-0228.wav|till every feature was obliterated, and then, still living, flung him into the sea.
LJSpeech-1.1/wavs/LJ003-0098.wav|the inevitable consequence of such a situation, their morals must have been destroyed;
LJSpeech-1.1/wavs/LJ006-0151.wav|Many of them were otherwise and improperly occupied for hours every day in menial services for the governor, cleaning his windows or grooming his horse.
LJSpeech-1.1/wavs/LJ007-0172.wav|where is to be found in operation every expedient by which Ignorance may be superseded by Knowledge, Idleness by Industry, and Suffering by Benevolence;
LJSpeech-1.1/wavs/LJ004-0034.wav|Moreover, the laws applied more particularly to county jurisdictions.
LJSpeech-1.1/wavs/LJ024-0099.wav|even though the thirty- five states with ninety-five percent of the population are in favor of it.
LJSpeech-1.1/wavs/LJ048-0263.wav|During entire periods of travel status,
LJSpeech-1.1/wavs/LJ011-0226.wav|which was based on his jail experiences, and of which I have availed myself in the last chapter.
LJSpeech-1.1/wavs/LJ041-0006.wav|His mother exercised little control over him and thought he could decide for himself whether to go on in school.
LJSpeech-1.1/wavs/LJ011-0267.wav|Mr. Gee had invested one thousand two hundred pounds of this, and was seeking how best to place the remaining eight hundred pounds,
LJSpeech-1.1/wavs/LJ002-0120.wav|had been issued for the arrests of debtors in the kingdom, for sums varying from fourpence to five hundred pounds and upwards.
LJSpeech-1.1/wavs/LJ014-0064.wav|He lived at Mile End, whence he walked often to call at three, Minver Place, Bermondsey, the residence of his old love.
LJSpeech-1.1/wavs/LJ027-0123.wav|where within the limits of the same natural group of organisms a rudiment is sometimes present and sometimes absent.
LJSpeech-1.1/wavs/LJ019-0224.wav|With the reduction of numbers to be accommodated, there was ample space in Newgate for its reconstruction on the most approved modern lines.
LJSpeech-1.1/wavs/LJ036-0031.wav|and requested a transfer which she might use if she got through the traffic.
LJSpeech-1.1/wavs/LJ025-0034.wav|Animals further needed muscles for locomotion and nerves for sensibility.
LJSpeech-1.1/wavs/LJ050-0106.wav|to devise a practical system which has any reasonable possibility of revealing such malcontents.
LJSpeech-1.1/wavs/LJ019-0066.wav|with the means of earning an honest livelihood if so disposed.
LJSpeech-1.1/wavs/LJ026-0011.wav|Because of these uncertain forms of life,
LJSpeech-1.1/wavs/LJ028-0515.wav|Such were the walls of Babylon,
LJSpeech-1.1/wavs/LJ016-0332.wav|who was convicted of complicity in the Clerkenwell explosion, intended to effect the release of Burke and Casey
LJSpeech-1.1/wavs/LJ028-0344.wav|for Cyrus had done neither the one nor the other when he took Babylon.
LJSpeech-1.1/wavs/LJ006-0032.wav|Messrs. Crawford and Russell proceeded to carry out their new functions with commendable energy, and without a moment's loss of time.
LJSpeech-1.1/wavs/LJ049-0187.wav|These proposals included suggestions to locate exclusive responsibility for all phases of the work
LJSpeech-1.1/wavs/LJ010-0063.wav|The massacre of the whole of the Cabinet Ministers at one stroke was to be followed by an attack
LJSpeech-1.1/wavs/LJ001-0139.wav|a blemish which can be nearly, though not wholly, avoided by care and forethought
LJSpeech-1.1/wavs/LJ045-0083.wav|On that issue George De Mohrenschildt, who was probably as close to the Oswalds as anyone else during their first stay in Dallas,
LJSpeech-1.1/wavs/LJ019-0264.wav|and it was decidedly of opinion that in all short sentences the hard labor of the tread-wheel, crank, and so forth should be the invariable rule.
LJSpeech-1.1/wavs/LJ015-0050.wav|Following this, warrants were issued for their arrest,
LJSpeech-1.1/wavs/LJ019-0040.wav|the difficulty of access, and the admitted necessity of giving architectural importance to this the national model prison.
LJSpeech-1.1/wavs/LJ012-0199.wav|After a little
LJSpeech-1.1/wavs/LJ020-0014.wav|beating the batter smooth as you go on until all of the liquid and flour has gone in.
LJSpeech-1.1/wavs/LJ009-0022.wav|I was informed that this unnecessarily harassed his feelings, and that the object of such sermons was solely to console the prisoner,
LJSpeech-1.1/wavs/LJ030-0024.wav|In Dallas the rain had stopped, and by midmorning a gloomy overcast sky had given way to the bright sunshine that greeted the Presidential party
LJSpeech-1.1/wavs/LJ047-0176.wav|shortly after Oswald rented the room on October fourteen.
LJSpeech-1.1/wavs/LJ013-0107.wav|but he escaped through a back door on to the river, and rowed off in a boat to a hiding-place in the woods.
LJSpeech-1.1/wavs/LJ008-0109.wav|As we crossed the press yard a cock crew, and the solitary clanking of a restless chain was dreadfully horrible.
LJSpeech-1.1/wavs/LJ018-0381.wav|the wildest and most cut-throat looking of the lot, which proves that he could be grateful for kindness, and was not all bad.
LJSpeech-1.1/wavs/LJ050-0135.wav|According to Secretary Dillon,
LJSpeech-1.1/wavs/LJ030-0247.wav|I was bent over under the weight of Agent Youngblood's body, toward Mrs. Johnson and Senator Yarborough, end quote,
LJSpeech-1.1/wavs/LJ012-0184.wav|Meanwhile the discovery of pistol and knife spattered with human blood and brains
LJSpeech-1.1/wavs/LJ021-0046.wav|there could be no recovery of public confidence in the security of savings.
LJSpeech-1.1/wavs/LJ042-0236.wav|In the second simulated transcript which ended with the statement, quote, Newspapers thank you, sir. You are a real patriot! End quote.
LJSpeech-1.1/wavs/LJ048-0002.wav|Chapter eight. The Protection of the President. Part three.
LJSpeech-1.1/wavs/LJ047-0199.wav|The Secret Service and the FBI differ
LJSpeech-1.1/wavs/LJ002-0238.wav|was used for debtors arrested for the lowest sums within twelve miles of the palace of Whitehall;
LJSpeech-1.1/wavs/LJ036-0072.wav|to Murphy and Elm three times, averaging six point five minutes for the three trips.
LJSpeech-1.1/wavs/LJ048-0220.wav|Conduct of Secret Service agents in Fort Worth on November twenty-two.
LJSpeech-1.1/wavs/LJ015-0208.wav|they sounded one Burgess, a guard on the South-Eastern Railway, a line by which large quantities of bullion were sent to the Continent.
LJSpeech-1.1/wavs/LJ043-0031.wav|I am surprised that he didn't do something worse, end quote.
LJSpeech-1.1/wavs/LJ002-0287.wav|There were no beds or bedding, no straw even.
LJSpeech-1.1/wavs/LJ003-0294.wav|This committee made its report in September the following year, and an excellent report it is, so far as its recommendations are concerned.
LJSpeech-1.1/wavs/LJ002-0256.wav|A committee of collegians was elected to act as the executive, also a secretary or accountant to receive monies and keep books,
LJSpeech-1.1/wavs/LJ034-0096.wav|on the southwest corner of Elm and Houston Streets, looking north at the Depository Building which was directly in front of him.
LJSpeech-1.1/wavs/LJ028-0308.wav|Let neither these nor the former troops be armed with any weapons but their swords those thou mayest leave them.
LJSpeech-1.1/wavs/LJ008-0004.wav|The reasons for this change were fully set forth in a previous chapter.
LJSpeech-1.1/wavs/LJ044-0080.wav|was apparently not enough to satisfy him. He exaggerated in his letters to V. T. Lee in an apparent attempt
LJSpeech-1.1/wavs/LJ006-0169.wav|He really did not know what passed in his jail
LJSpeech-1.1/wavs/LJ040-0098.wav|Marguerite Oswald worked in miscellaneous jobs after her divorce from Ekdahl.
LJSpeech-1.1/wavs/LJ038-0306.wav|was considered of probative value in this investigation, although the Commission's conclusion concerning the identity of the assassin
LJSpeech-1.1/wavs/LJ038-0187.wav|I paid for the box last month so don't worry about it.
LJSpeech-1.1/wavs/LJ015-0243.wav|At Redhill Tester met the train and relieved the thieves of a portion of the stolen gold.
LJSpeech-1.1/wavs/LJ005-0191.wav|The Society proceeded to support this indictment by facts. It is much the old story.
LJSpeech-1.1/wavs/LJ037-0028.wav|He saw him empty the gun and throw the shells into some bushes on the southeast corner lot.
LJSpeech-1.1/wavs/LJ010-0011.wav|This led to a rapid and marked increase in all kinds of fraud;
LJSpeech-1.1/wavs/LJ043-0020.wav|The relations between Oswald and his wife became such that Bouhe wanted to "liberate" her from Oswald.
LJSpeech-1.1/wavs/LJ011-0177.wav|The fact was, Wakefield went on to say, an uncle of his had advanced Mr. Turner sixty thousand pounds, which had temporarily staved off ruin.
LJSpeech-1.1/wavs/LJ028-0434.wav|the large high mound, which resembles a mountain from a distance, still bears the ancient name Babel.
LJSpeech-1.1/wavs/LJ042-0202.wav|It has turned itself into the traditional lever of a foreign power to overthrow the government of the United States;
LJSpeech-1.1/wavs/LJ027-0074.wav|Sometimes a piece is enlarged, sometimes diminished, or even becomes obsolete; sometimes several pieces are consolidated into one;
LJSpeech-1.1/wavs/LJ006-0145.wav|He could indulge in snuff if a snuff-taker,
LJSpeech-1.1/wavs/LJ035-0001.wav|Report of the President's Commission on the Assassination of President Kennedy. The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
LJSpeech-1.1/wavs/LJ012-0162.wav|Having brought down the records of great frauds, forgeries, and thefts from about eighteen twenty-five to eighteen forty,
LJSpeech-1.1/wavs/LJ039-0021.wav|I called him into the bathroom and I closed the door and I wanted to prevent him and then I started to cry.
LJSpeech-1.1/wavs/LJ017-0128.wav|At the last moment Palmer tossed a bit of paper over to his counsel, on which he had written, quote, I think there will be a verdict of Not Guilty, end quote.
LJSpeech-1.1/wavs/LJ043-0143.wav|with his recently acquired rifle and pistol, a copy of the March twenty-four, nineteen sixty-three, issue of the Worker,
LJSpeech-1.1/wavs/LJ035-0147.wav|Mrs. Reid had watched the parade from the sidewalk in front of the building with Truly and Mr. O. V. Campbell, vice president of the Depository.
LJSpeech-1.1/wavs/LJ048-0092.wav|The advance preparations in Dallas by Agent Winston G. Lawson of the White House detail have been described in chapter two.
LJSpeech-1.1/wavs/LJ006-0179.wav|But, indeed, his whole rule was far too mild, and under this mistaken leniency
LJSpeech-1.1/wavs/LJ017-0187.wav|Her husband, who came up to town, would not allow a post-mortem, and again Mrs. Wilson escaped.
LJSpeech-1.1/wavs/LJ028-0132.wav|Yet as large and lofty as they were, they were completed in fifteen days.
LJSpeech-1.1/wavs/LJ042-0053.wav|Responding to Robert's statement that he had not "renounced" him,
LJSpeech-1.1/wavs/LJ009-0112.wav|the burglar muttering curses and savage expressions of defiance; whilst the poor sheep-stealer shakes hands with the turnkeys,
LJSpeech-1.1/wavs/LJ019-0150.wav|Captain Williams, who was the inspector of prisons for the home district in succession to Messrs. Crawford and Russell,
LJSpeech-1.1/wavs/LJ030-0020.wav|if anybody really wanted to shoot the President of the United States, it was not a very difficult job
LJSpeech-1.1/wavs/LJ029-0033.wav|particularly in large cities where the purpose was to let the President be seen by as many people as possible.
LJSpeech-1.1/wavs/LJ028-0098.wav|the wise, the pious, the maintainer of Esagil and Ezida,
LJSpeech-1.1/wavs/LJ028-0014.wav|The desert about you shows no signs of life;
LJSpeech-1.1/wavs/LJ003-0346.wav|It pointed out that the Government was to blame for the overcrowding, and might diminish it if it chose.
LJSpeech-1.1/wavs/LJ038-0214.wav|and the other paragraphs instructed her on the disposal of Oswald's personal effects and the management of her affairs if he should not return.
LJSpeech-1.1/wavs/LJ050-0122.wav|It should be made clear that the Secret Service will in no way seek to duplicate the intelligence
LJSpeech-1.1/wavs/LJ018-0143.wav|each containing two notes, many of the sheets suitable for engraving any kind of note from one thousand pounds downwards.
LJSpeech-1.1/wavs/LJ023-0126.wav|In other words, we said we would seek an amendment only if every other possible means by legislation were to fail.
LJSpeech-1.1/wavs/LJ048-0015.wav|We talked to him twice.
LJSpeech-1.1/wavs/LJ049-0179.wav|The Commission believes that both the FBI and the Secret Service have too narrowly construed their respective responsibilities.
LJSpeech-1.1/wavs/LJ050-0269.wav|The essential terms of such memoranda might well be embodied in an Executive order.
LJSpeech-1.1/wavs/LJ006-0265.wav|The untried might see their friends three times a week, the convicted only once.
LJSpeech-1.1/wavs/LJ013-0160.wav|who, on going down early, was surprised to find the dining-room in a state of utter confusion;
LJSpeech-1.1/wavs/LJ032-0040.wav|were written the words "A. Hidell, P.O. Box two nine one five Dallas, Texas."
LJSpeech-1.1/wavs/LJ006-0261.wav|together with four bradawls, several large iron spikes, screws, nails, and knives;
LJSpeech-1.1/wavs/LJ033-0114.wav|When Frazier appeared before the Commission and was asked to demonstrate how Oswald carried the package, he said, quote, Like I said,
LJSpeech-1.1/wavs/LJ034-0163.wav|The Commission is satisfied that, at the least,
LJSpeech-1.1/wavs/LJ032-0125.wav|In his testimony before the Commission, Latona stated that when he received the rifle, the area where prints were visible was protected by cellophane.
LJSpeech-1.1/wavs/LJ008-0189.wav|All the avenues and approaches, places even whence nothing whatever could be seen of the scaffold,
LJSpeech-1.1/wavs/LJ016-0334.wav|Unusual precautions were taken upon this occasion, as some fresh outrage was apprehended.
LJSpeech-1.1/wavs/LJ006-0114.wav|They bought their offices from one another, and were thus considered to have a vested interest in them.
LJSpeech-1.1/wavs/LJ007-0214.wav|"The prominent evils of this prison (Newgate) -- evils which the alterations made within the last four years have failed to remove
LJSpeech-1.1/wavs/LJ005-0213.wav|Newgate through all these years continued a bye-word with the Society.
LJSpeech-1.1/wavs/LJ013-0011.wav|She was freighted by the firm of Zulueta and Co. for a voyage to Santa Cruz.
LJSpeech-1.1/wavs/LJ009-0249.wav|When Charles White was executed in eighteen twenty-three for arson, he arranged a handkerchief
LJSpeech-1.1/wavs/LJ039-0005.wav|Richard M. Nixon Incident
LJSpeech-1.1/wavs/LJ019-0083.wav|The discipline also varied greatly, from the severely penal to the culpably lax.
LJSpeech-1.1/wavs/LJ037-0217.wav|Police found an empty revolver holster when they searched Oswald's room on Beckley Avenue after his arrest.
LJSpeech-1.1/wavs/LJ042-0117.wav|he noted that one of his acquaintances, quote, relates many things I do not know about the U.S.S.R.
LJSpeech-1.1/wavs/LJ008-0035.wav|were told that the plan had been well considered, and would be persevered in.
LJSpeech-1.1/wavs/LJ048-0016.wav|He likewise indicated he was disenchanted with Russia.
LJSpeech-1.1/wavs/LJ014-0130.wav|Manning, when sentence of death was passed on him, said nothing;
LJSpeech-1.1/wavs/LJ026-0050.wav|following in part the comparisons of certain animals and plants by Sedgwick and Wilson and others.
LJSpeech-1.1/wavs/LJ009-0044.wav|His features have no felonious cast;
LJSpeech-1.1/wavs/LJ010-0024.wav|While the varying conditions of social life thus brought about many changes in the character of offenses against property,
LJSpeech-1.1/wavs/LJ047-0021.wav|information regarding his relations with the U.S. Embassy in Moscow and background data relating largely to his prior military service,
LJSpeech-1.1/wavs/LJ012-0224.wav|who examined Bishop and his fellows, and further incriminating evidence adduced, to the effect that the prisoners had bartered for a coach to carry "a stiff 'un";
LJSpeech-1.1/wavs/LJ019-0096.wav|other authorities as strongly condemned it as brutalizing, unequal in its operation, and altogether a "deplorable invention."
LJSpeech-1.1/wavs/LJ006-0048.wav|To these were still added an average of about fifty expecting the last penalty of the law; a certain number of transports awaiting removal to the colonies;
LJSpeech-1.1/wavs/LJ038-0277.wav|I am aware of their position. This is not, I am sure, arrived at without careful consideration.
LJSpeech-1.1/wavs/LJ041-0170.wav|Thornley testified, quote, At which time he looked at me like a betrayed Caesar and screamed, screamed definitely, "Not you, too, Thornley!"
LJSpeech-1.1/wavs/LJ046-0136.wav|Before the assassination of President Kennedy,
LJSpeech-1.1/wavs/LJ029-0056.wav|Although there was no mention in PRS files of the demonstration in Dallas against Ambassador Adlai Stevenson on October twenty-fourth,
LJSpeech-1.1/wavs/LJ007-0217.wav|They go on to say
LJSpeech-1.1/wavs/LJ046-0194.wav|Members of the White House detail were expected to familiarize themselves with the descriptions and photographs of the highest risk cases.
LJSpeech-1.1/wavs/LJ038-0239.wav|indicated that the bullet was fired from a position near the point where one of the photographs was taken.
LJSpeech-1.1/wavs/LJ008-0263.wav|Forty-eight hours was the limit of time allowed to the unhappy man to make his peace, and during that time he was still kept on a bare allowance of bread and water.
LJSpeech-1.1/wavs/LJ023-0084.wav|When the Congress has sought to stabilize national agriculture, to improve the conditions of labor,
LJSpeech-1.1/wavs/LJ039-0146.wav|Marina Oswald testified that in New Orleans in May of nineteen sixty-three, she observed Oswald sitting with the rifle on their screened porch at night,
LJSpeech-1.1/wavs/LJ039-0226.wav|the Marine marksmanship experts, Major Anderson and Sergeant Zahm, concurred in the opinion that Oswald had the capability to fire three shots,
LJSpeech-1.1/wavs/LJ049-0076.wav|The Commission's review of the provisions for Presidential protection at the time of President Kennedy's trip to Dallas demonstrates the need for substantial improvements.
LJSpeech-1.1/wavs/LJ014-0293.wav|He returned from court in a state of gloomy dejection,
LJSpeech-1.1/wavs/LJ043-0033.wav|Bouhe thoroughly disapproved of this and as a result almost all communication between the Oswalds and members of the Russian community ceased.
LJSpeech-1.1/wavs/LJ023-0035.wav|For in the last three national elections
LJSpeech-1.1/wavs/LJ028-0001.wav|The Seven Wonders of the Ancient World. By Edgar J. Banks. Chapter two. The Walls of Babylon.
LJSpeech-1.1/wavs/LJ007-0095.wav|Prisoners indeed were known to boast that they had saved their necks by feigning insanity.
LJSpeech-1.1/wavs/LJ002-0237.wav|This very ancient prison, which stood in the High Street, Southwark,
LJSpeech-1.1/wavs/LJ036-0182.wav|She recalled that it was subsequent to the time the President had been shot.
LJSpeech-1.1/wavs/LJ032-0089.wav|It certified that Lee Harvey Oswald had been vaccinated for smallpox on June eight, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ043-0018.wav|He was offensive with the people. And I can understand why, because that hurt him.
LJSpeech-1.1/wavs/LJ048-0210.wav|He was handicapped, however, by the fact that he was riding in a closed car whose roof at times obscured his view.
LJSpeech-1.1/wavs/LJ033-0074.wav|Marina Oswald testified that this was her first knowledge that the rifle was not in its accustomed place.
LJSpeech-1.1/wavs/LJ040-0195.wav|It appears that he did not want to do any of the things which the authorities suggested in their efforts to bring him out of the shell
LJSpeech-1.1/wavs/LJ007-0183.wav|traversing where it was possible the statements of the inspectors, and offering explanation and palliation of such evils as could not be denied.
LJSpeech-1.1/wavs/LJ038-0232.wav|Marina Oswald stated that when Oswald returned home on the night of the Walker shooting, he told her that he had been planning the attempt for two months.
LJSpeech-1.1/wavs/LJ031-0055.wav|Dr. Perry noted the President's back brace as he felt for a femoral pulse, which he did not find.
LJSpeech-1.1/wavs/LJ018-0332.wav|Greed in the latter case was a secondary motive;
LJSpeech-1.1/wavs/LJ022-0001.wav|The Fireside Chats of Franklin Delano Roosevelt, by Franklin D Roosevelt, Section seven.
LJSpeech-1.1/wavs/LJ024-0107.wav|The first includes those who fundamentally object to social and economic legislation along modern lines.
LJSpeech-1.1/wavs/LJ030-0070.wav|Motorcycles. -- Four motorcycles, two on each side, flanked the rear of the Presidential car.
LJSpeech-1.1/wavs/LJ025-0048.wav|Respiration -- that is, the absorption of oxygen and the exhalation of carbonic acid
LJSpeech-1.1/wavs/LJ038-0237.wav|The Commission confirmed, by comparison with other photographs, that these were, indeed, photographs of the rear of Walker's house.
LJSpeech-1.1/wavs/LJ043-0032.wav|After about a two-week separation, Marina Oswald returned to her husband.
LJSpeech-1.1/wavs/LJ021-0177.wav|Did England hold to the gold standard when her reserves were threatened?
LJSpeech-1.1/wavs/LJ001-0089.wav|but his letters, though uninteresting and poor, are not nearly so gross and vulgar as those of either the Italian or the Frenchman.
LJSpeech-1.1/wavs/LJ034-0210.wav|The picture which gave rise to these allegations was taken by Associated Press Photographer James W. Altgens,
LJSpeech-1.1/wavs/LJ010-0272.wav|This son, John William Bean, was fully identified by Dasset, and presently examined by the Privy Council.
LJSpeech-1.1/wavs/LJ012-0179.wav|The others followed, and on overtaking Thurtell, found he had done the job alone in a retired part of the road known as Gill's Hill Lane.
LJSpeech-1.1/wavs/LJ032-0126.wav|He examined these prints, as well as photographs of them which the Dallas police had made, and concluded that:
LJSpeech-1.1/wavs/LJ016-0413.wav|No less than sixty-seven persons were present, admitted by special permission of the sheriff.
LJSpeech-1.1/wavs/LJ010-0032.wav|Pegsworth, and Greenacre, and Daniel Good merely reproduced types that had gone before, and that have since reappeared.
LJSpeech-1.1/wavs/LJ029-0015.wav|The party itself saw an opportunity to raise funds by having the President speak at a political dinner eventually planned for Austin.
LJSpeech-1.1/wavs/LJ033-0169.wav|it would be the thickness of both the paper and the tape, the color under various lighting conditions of both the paper and the tape,
LJSpeech-1.1/wavs/LJ047-0121.wav|stated the Bureau's reasoning in this way, quote,
LJSpeech-1.1/wavs/LJ021-0197.wav|of referring without rhyme or reason to the Constitution as a means of preventing its accomplishment, thus creating the general impression
LJSpeech-1.1/wavs/LJ004-0216.wav|The most noticeable of the improvements introduced was a better regulation of dietaries within the prison.
LJSpeech-1.1/wavs/LJ042-0162.wav|Full of optimism and hope, he stood in Red Square in the Fall of nineteen fifty-nine, vowing to see his chosen course through,
LJSpeech-1.1/wavs/LJ012-0008.wav|He had sought by all legal means to obtain possession of the two thousand pounds, but had failed, and had had recourse to more violent means.
LJSpeech-1.1/wavs/LJ036-0191.wav|he would have reached tenth and Patton shortly after one:fifteen p.m.
LJSpeech-1.1/wavs/LJ010-0137.wav|Davidson, who was the only one who seemed to realize his awful situation, listened patiently and with thankfulness to the chaplain,
LJSpeech-1.1/wavs/LJ006-0063.wav|minor offenders charged with small thefts or non-payment of small sums were cheek by jowl with convicts sentenced to long terms of transportation.
LJSpeech-1.1/wavs/LJ022-0188.wav|Certain proposals made to amend the Federal Reserve Act deserve prompt and favorable action by the Congress.
LJSpeech-1.1/wavs/LJ039-0026.wav|she stated that she might have been confused about shutting him in the bathroom, but that, quote, there is no doubt that he got dressed and got a gun, end quote,
LJSpeech-1.1/wavs/LJ038-0036.wav|As McDonald started to search Oswald's waist for a gun, he heard him say, quote, Well, it's all over now, end quote.
LJSpeech-1.1/wavs/LJ041-0146.wav|it was more in terms of a general hostility against the government and its representatives rather than a grudge against any particular person.
LJSpeech-1.1/wavs/LJ034-0128.wav|But the testimony of these employees, together with photographs subsequently taken of them at the scene of the assassination,
LJSpeech-1.1/wavs/LJ039-0121.wav|and he probably didn't have as high a motivation because he was no longer in recruit training and under the care of the drill instructor.
LJSpeech-1.1/wavs/LJ011-0182.wav|Miss Turner, thus pressed, consented to go on to Gretna Green.
LJSpeech-1.1/wavs/LJ008-0042.wav|is enclosed by a temporary roof, under which are placed two seats for the reception of the sheriffs, one on each side of the stairs leading to the scaffold.
LJSpeech-1.1/wavs/LJ026-0135.wav|If a larger quantity of starch is formed in the chlorophyll bodies than is immediately needed by the protoplasm for purposes of repair or growth,
LJSpeech-1.1/wavs/LJ003-0226.wav|The rations of food were notoriously inadequate, and so carelessly distributed, that many were left to starve.
LJSpeech-1.1/wavs/LJ044-0115.wav|he felt that this was a great man that he had received the letter from, end quote.
LJSpeech-1.1/wavs/LJ011-0270.wav|but on arrival he was met by a young sailor with a letter which begged Mr. Gee to go to Heath's house, as the latter was not well.
LJSpeech-1.1/wavs/LJ016-0105.wav|These men were all in prison dress at the time of their escape, but one of their number, Bell, sent back his clothes a few days later by parcel's delivery,
LJSpeech-1.1/wavs/LJ003-0033.wav|Enough has been said, probably, to prove that there was room for improvement in the condition and treatment of debtors in the prisons of the city of London.
LJSpeech-1.1/wavs/LJ036-0156.wav|He was in error, however.
LJSpeech-1.1/wavs/LJ028-0039.wav|We know the names of its kings, and the records speak of long wars with the Assyrians.
LJSpeech-1.1/wavs/LJ046-0089.wav|His travel would be in secret; his public appearances would be behind bulletproof glass. A more practical approach necessitates compromise.
LJSpeech-1.1/wavs/LJ004-0110.wav|It was made incumbent upon the justices to provide distinct places of confinement for five classes of prisoners, viz.
LJSpeech-1.1/wavs/LJ032-0091.wav|There is no "Dr. Hideel" licensed to practice medicine in Louisiana.
LJSpeech-1.1/wavs/LJ038-0171.wav|General Walker gave this information to the police before the shooting, but it did not help solve the crime.
LJSpeech-1.1/wavs/LJ034-0159.wav|The Commission, therefore, does not base its conclusion concerning the identity of the assassin
LJSpeech-1.1/wavs/LJ018-0375.wav|The 'Lennie's' men were all Greeks, except one known as French Peter,
LJSpeech-1.1/wavs/LJ004-0113.wav|It was further ordered that male prisoners should be kept perfectly distinct from the females.
LJSpeech-1.1/wavs/LJ030-0250.wav|Other Secret Service agents assigned to the motorcade remained at their posts during the race to the hospital.
LJSpeech-1.1/wavs/LJ035-0011.wav|a strong wind blowing from the north almost unseated him.
LJSpeech-1.1/wavs/LJ037-0161.wav|and impressed upon the lead of the bullets inconsistent individual characteristics which made identification impossible.
LJSpeech-1.1/wavs/LJ034-0156.wav|whether or not he could positively identify the man he saw in the sixth-floor window as the same man he saw in the police station,
LJSpeech-1.1/wavs/LJ003-0108.wav|Spirits were freely introduced, and although he at first abstained,
LJSpeech-1.1/wavs/LJ048-0074.wav|To insure adequate and effective liaison arrangements,
LJSpeech-1.1/wavs/LJ031-0188.wav|Members of the Presidential and Vice-Presidential parties filled the central compartment of the plane to witness the swearing in.
LJSpeech-1.1/wavs/LJ018-0232.wav|He himself prepared it on a blank form which he had brought with him on purpose.
LJSpeech-1.1/wavs/LJ029-0125.wav|The only practical way for westbound traffic on Main Street
LJSpeech-1.1/wavs/LJ017-0196.wav|The last time Mrs. Soames showed great reluctance to take it, but Wilson said it would certainly do her good.
LJSpeech-1.1/wavs/LJ030-0152.wav|Speed of the Limousine
LJSpeech-1.1/wavs/LJ004-0238.wav|Mr. Buxton mentions the case of a boy whose apparent innocence and artlessness had attracted his attention.
LJSpeech-1.1/wavs/LJ032-0237.wav|it was established that the photographs must have been taken sometime after March twenty-seven.
LJSpeech-1.1/wavs/LJ024-0130.wav|to frighten the workers of America in a pay-envelope propaganda against the Social Security Law.
LJSpeech-1.1/wavs/LJ044-0129.wav|and often it is advisable for some people to remain in the background, not underground, end quote.
LJSpeech-1.1/wavs/LJ039-0124.wav|End quote. Major Anderson concluded, quote, I would say that as compared to other Marines receiving the same type of training,
LJSpeech-1.1/wavs/LJ025-0167.wav|and in the seeds which it produces are exactly equivalent to the weights of the same elements which have disappeared from the materials supplied to the bean during its growth.
LJSpeech-1.1/wavs/LJ042-0033.wav|of his concomitant hatred of the United States, which was most clearly expressed in his November twenty-six,
LJSpeech-1.1/wavs/LJ046-0228.wav|the Secret Service had no standard procedure for the systematic review of its requests for and receipt of information from other Federal agencies.
LJSpeech-1.1/wavs/LJ039-0159.wav|The ammunition used by the assassin was manufactured by Western Cartridge Co. of East Alton, Illinois.
LJSpeech-1.1/wavs/LJ028-0104.wav|lined the shores of the rivers with embankments, and spanned the rivers with bridges.
LJSpeech-1.1/wavs/LJ023-0102.wav|subsistence, and health of large numbers in the community, then
LJSpeech-1.1/wavs/LJ041-0136.wav|was shooting at Connally rather than President Kennedy, end quote.
LJSpeech-1.1/wavs/LJ045-0129.wav|has visited us here in Dallas, Texas, on November one. Agent James P. Hasty
LJSpeech-1.1/wavs/LJ022-0115.wav|This is a great national crusade to destroy enforced idleness which is an enemy of the human spirit
LJSpeech-1.1/wavs/LJ047-0087.wav|According to the Bureau, quote,
LJSpeech-1.1/wavs/LJ005-0242.wav|In the year immediately preceding this, Parliament was too busy with the great question of its own reform to spare much time for domestic legislation.
LJSpeech-1.1/wavs/LJ032-0252.wav|Marina Oswald has stated that the rifle was among these possessions, although Ruth Paine testified that she was not aware of it.
LJSpeech-1.1/wavs/LJ044-0225.wav|It should also be noted, however, that one witness testified that shortly before the assassination
LJSpeech-1.1/wavs/LJ018-0085.wav|He would shoot any man or any policeman like a dog, or any number of them, who had treated him in that way.
LJSpeech-1.1/wavs/LJ014-0105.wav|He was lying on his face, his legs tied up to his hips so as to allow of the body fitting into the hole.
LJSpeech-1.1/wavs/LJ012-0290.wav|While conversing with Mrs. Brown, he declared the unfortunate woman was rocking herself to and fro in a chair;
LJSpeech-1.1/wavs/LJ028-0505.wav|It seems that the bricks of the reliefs were molded and glazed separately and so accurately that when built into the wall they fitted perfectly.
LJSpeech-1.1/wavs/LJ036-0068.wav|Both buses stopped within one block of the Depository Building.
LJSpeech-1.1/wavs/LJ018-0011.wav|About the same time a body was discovered on the line near the railway-bridge by Victoria Park.
LJSpeech-1.1/wavs/LJ050-0267.wav|between Secretary Dillon and Donald F. Hornig, Special Assistant to the President for Science and Technology, is a useful effort in the right direction.
LJSpeech-1.1/wavs/LJ043-0041.wav|Consistent with this attitude
LJSpeech-1.1/wavs/LJ039-0171.wav|On the second series they required five point one five, six point four five, and seven seconds.
LJSpeech-1.1/wavs/LJ047-0084.wav|and his application was approved on the following day.
LJSpeech-1.1/wavs/LJ013-0088.wav|the cashier gave them eight Bank of England notes for one thousand pounds each, saying that they could get so much specie nowhere else.
LJSpeech-1.1/wavs/LJ032-0001.wav|Report of the President's Commission on the Assassination of President Kennedy. The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
LJSpeech-1.1/wavs/LJ018-0125.wav|Burnett had only just come out of jail after completing a sentence of penal servitude.
LJSpeech-1.1/wavs/LJ005-0218.wav|The chapel still continued incommodious and insufficient
LJSpeech-1.1/wavs/LJ022-0082.wav|In all cases projects must be of a character to give employment to those on the relief rolls.
LJSpeech-1.1/wavs/LJ042-0201.wav|He wrote, quote, The Communist Party of the United States has betrayed itself!
LJSpeech-1.1/wavs/LJ002-0069.wav|to the various wards their friends occupied.
LJSpeech-1.1/wavs/LJ023-0133.wav|judges who will retain in the courts the judicial functions of a court,
LJSpeech-1.1/wavs/LJ044-0239.wav|and raises serious questions as to whether or not he ever expected to escape.
LJSpeech-1.1/wavs/LJ007-0186.wav|the undue authority given to prisoners, the levying of garnish under another name
LJSpeech-1.1/wavs/LJ009-0078.wav|who preaches plain, homely discourses, as fit as any religious discourse can be fit for the irritated audience.
LJSpeech-1.1/wavs/LJ010-0311.wav|in other words, he forged powers of attorney, and proceeded to realize securities lodged in his bank under various names.
LJSpeech-1.1/wavs/LJ015-0159.wav|In his person he was neat and fastidious;
LJSpeech-1.1/wavs/LJ016-0322.wav|the commission recommended that death sentences should be carried out within the jail, under such regulations as might be considered necessary
LJSpeech-1.1/wavs/LJ038-0223.wav|from October nine, nineteen sixty-two, to May fourteen, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ016-0016.wav|There is an attempt at escape mentioned in Mr. Wakefield's book, which might have been an intended suicide.
LJSpeech-1.1/wavs/LJ024-0091.wav|Each one is radically different from the other.
LJSpeech-1.1/wavs/LJ021-0116.wav|We also question the wisdom of extending code requirements suited to the great industrial centers and to large employers,
LJSpeech-1.1/wavs/LJ031-0033.wav|Then he experienced his first sensation of pain, which became excruciating.
LJSpeech-1.1/wavs/LJ018-0377.wav|Conviction was obtained through the evidence of the steward and two of the least culpable of the crew.
LJSpeech-1.1/wavs/LJ012-0082.wav|Jordan and Sullivan, who at once set to work in a business-like way to obtain impressions of the keys of the strong room and chest.
LJSpeech-1.1/wavs/LJ015-0026.wav|Moreover, the partners were sober, steady men, who paid unremitting attention to business.
LJSpeech-1.1/wavs/LJ045-0039.wav|His past relationships with his wife had been stormy, however, and it did not seem that she respected him very much.
LJSpeech-1.1/wavs/LJ030-0073.wav|Presidential follow-up car.
LJSpeech-1.1/wavs/LJ025-0045.wav|They get rid of the superfluous hydrogen and carbon and accumulate nitrogen.
LJSpeech-1.1/wavs/LJ005-0204.wav|Clun, in Shropshire, had a lock-up under the town hall.
LJSpeech-1.1/wavs/LJ001-0024.wav|But the first Bible actually dated (which also was printed at Maintz by Peter Schoeffer in the year fourteen sixty-two)
LJSpeech-1.1/wavs/LJ026-0111.wav|In the cells the foods undergo metabolic changes.
LJSpeech-1.1/wavs/LJ010-0109.wav|Thistlewood made a long and rambling defense, the chief features of which were abuse of Lord Sidmouth, and the vilification of the informer Edwards.
LJSpeech-1.1/wavs/LJ038-0188.wav|two. Send the information as to what has happened to me to the Embassy.
LJSpeech-1.1/wavs/LJ012-0139.wav|Solomons, had sold bar gold to the value of one thousand two hundred pounds to certain bullion dealers.
LJSpeech-1.1/wavs/LJ019-0112.wav|Such excellent returns might be counted upon, that a margin of profit would be left after the cost of the prisons had been defrayed.
LJSpeech-1.1/wavs/LJ033-0107.wav|No other employee has been found who saw Oswald enter that morning.
LJSpeech-1.1/wavs/LJ042-0189.wav|but one with union communes,
LJSpeech-1.1/wavs/LJ018-0079.wav|The unfortunate man survived till he landed, but died in Guy's Hospital.
LJSpeech-1.1/wavs/LJ035-0040.wav|As Baker reached the second floor, he was about twenty feet from the vestibule door. He intended to continue around to his left toward the stairway going up
LJSpeech-1.1/wavs/LJ046-0163.wav|During the period November nineteen sixty-one to November nineteen sixty-three,
LJSpeech-1.1/wavs/LJ038-0103.wav|On the afternoon of November twenty-three, Officers H. M. Moore,
LJSpeech-1.1/wavs/LJ014-0247.wav|and without reference to or comparison with the documents in which the payment was claimed.
LJSpeech-1.1/wavs/LJ037-0225.wav|five foot eight inches, black hair, slender, wearing a white jacket, white shirt and dark slacks, end quote,
LJSpeech-1.1/wavs/LJ010-0119.wav|It was asserted, not without foundation, at these trials, that Edwards repeatedly incited the associates he was betraying
LJSpeech-1.1/wavs/LJ018-0037.wav|In searching the prisoner's box, Mr. Briggs' watch was found wrapped up in a piece of leather,
LJSpeech-1.1/wavs/LJ033-0173.wav|The papers I also found were similar in fiber composition, therefore, in addition to the visual characteristics,
LJSpeech-1.1/wavs/LJ012-0113.wav|After their arrest, Jordan's wife and Sullivan's brother came to the inn, and begged to be allowed to visit this room;
LJSpeech-1.1/wavs/LJ030-0004.wav|The trip to Texas began with the departure of President and Mrs. Kennedy from the White House
LJSpeech-1.1/wavs/LJ042-0090.wav|I'm sure Russians will accept me after this sign of my faith in them, end quote.
LJSpeech-1.1/wavs/LJ044-0203.wav|For example, the Dallas Times Herald of November nineteen, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ012-0243.wav|There were many features of resemblance in these crimes.
LJSpeech-1.1/wavs/LJ008-0247.wav|but ever the same form moved along in the fulfillment of his mission, in spite of all persecution.
LJSpeech-1.1/wavs/LJ005-0258.wav|embodying recommendations which may be said to have formed the basis of modern prison management.
LJSpeech-1.1/wavs/LJ017-0064.wav|he made use of the remarkable words, quote, If it is necessary for my soul's sake to confess this murder,
LJSpeech-1.1/wavs/LJ016-0188.wav|He told Calcraft that he was Foxen the executioner, and that he was that moment on his way to Newgate to hang a man,
LJSpeech-1.1/wavs/LJ048-0190.wav|If such instructions were in fact given, they were not effectively carried out.
LJSpeech-1.1/wavs/LJ037-0197.wav|and the return address was Post Office Box two nine one five, Dallas, Texas.
LJSpeech-1.1/wavs/LJ025-0077.wav|Their food is provided for them,
LJSpeech-1.1/wavs/LJ030-0217.wav|quote, Mrs. Kennedy had jumped up from the seat and was, it appeared to me, reaching for something coming off the fight rear bumper of the car,
LJSpeech-1.1/wavs/LJ005-0175.wav|At this time there were in England one hundred and seventy boroughs, cities, towns, and liberties
LJSpeech-1.1/wavs/LJ006-0182.wav|Under the reckless contempt for regulations,
LJSpeech-1.1/wavs/LJ019-0302.wav|In eighteen sixty-two there were in all one hundred and ninety-three jails in England and Wales;
LJSpeech-1.1/wavs/LJ036-0202.wav|At twelve:fifty-four p.m., Tippit reported that he was in the central Oak Cliff area at Lancaster and Eighth.
LJSpeech-1.1/wavs/LJ018-0083.wav|Sattler was a very excitable although not an ill-tempered man.
LJSpeech-1.1/wavs/LJ032-0207.wav|I found it to be the same general configuration. All appearances were the same, end quote,
LJSpeech-1.1/wavs/LJ015-0018.wav|and dated back to the Commonwealth, when, under the title of Snow and Walton, it carried on business as pawnbrokers.
LJSpeech-1.1/wavs/LJ035-0089.wav|No allowance was made for the special conditions which existed on the day of the assassination
LJSpeech-1.1/wavs/LJ012-0094.wav|While the excitement was still fresh, a new robbery of diamonds was committed at a bonded warehouse in the immediate neighborhood, on Custom House Quay.
LJSpeech-1.1/wavs/LJ045-0004.wav|It has been suggested that one of the motivating influences operating on Lee Oswald was the atmosphere in the city of Dallas,
LJSpeech-1.1/wavs/LJ030-0036.wav|Secret Service arrangements for Presidential trips, which were followed in the Dallas motorcade,
LJSpeech-1.1/wavs/LJ010-0307.wav|New liabilities were incurred to the extent of one hundred thousand pounds by more failures, and in eighteen nineteen,
LJSpeech-1.1/wavs/LJ024-0038.wav|that no President fit for his office would appoint,
LJSpeech-1.1/wavs/LJ008-0301.wav|during which they counted the moments -- the prisoners in their cells as usual, and their friends in the street in front of Newgate, where they passed the night.
LJSpeech-1.1/wavs/LJ028-0073.wav|The walls of the palaces of many of the Assyrian kings were lined with great stone slabs engraved with reliefs and sometimes with the portrait of a king.
LJSpeech-1.1/wavs/LJ019-0022.wav|On the other hand, it must be admitted
LJSpeech-1.1/wavs/LJ001-0109.wav|this is best furthered by the avoidance of irrational swellings and spiky projections, and by the using of careful purity of line.
LJSpeech-1.1/wavs/LJ041-0149.wav|He told Aline Mosby, a reporter who interviewed him after he arrived in Moscow, quote,
LJSpeech-1.1/wavs/LJ028-0092.wav|Read the introduction to any of his inscriptions, of which the following is one, and you will call him vain and proud,
LJSpeech-1.1/wavs/LJ002-0073.wav|Neild takes it for granted that the former rather than the latter prevailed in the selection,
LJSpeech-1.1/wavs/LJ042-0178.wav|He thought the new alternative would have its best chance to be accepted after, quote, conflict between the two world systems leaves the world country
LJSpeech-1.1/wavs/LJ045-0224.wav|and such a favorable opportunity to strike at a figure as great as the President would probably never have come to him again.
LJSpeech-1.1/wavs/LJ021-0105.wav|and the vital necessity of improving labor conditions,
LJSpeech-1.1/wavs/LJ017-0142.wav|Smethurst's escape may have influenced the jury in the Poplar poisoning case,
LJSpeech-1.1/wavs/LJ005-0115.wav|or an imaginary boundary line, and nothing prevented parties from passing to either side
LJSpeech-1.1/wavs/LJ039-0038.wav|throughout April. The Commission asked Marina Oswald whether she might have misunderstood the object of her husband's threat. She stated, quote,
LJSpeech-1.1/wavs/LJ005-0005.wav|Even then they were not certain of the favor, for I find a reference to a decent and respectable woman sent to Newgate
LJSpeech-1.1/wavs/LJ029-0057.wav|nineteen sixty-three, Lawson inquired about the incident and obtained through the local police photographs of some of the persons involved.
LJSpeech-1.1/wavs/LJ003-0013.wav|No attempt was made to check drunkenness, beyond the penalty of shutting out friends from any ward in which a prisoner exceeded.
LJSpeech-1.1/wavs/LJ024-0081.wav|But we cannot yield our constitutional destiny to the personal judgment of a few men who, being fearful of the future,
LJSpeech-1.1/wavs/LJ028-0068.wav|They tell how he forced the exiles to carry heavy bags of sand across the desert to increase their burdens;
LJSpeech-1.1/wavs/LJ005-0200.wav|Most of these small jails were still in existence and in much the same state eight years later,
LJSpeech-1.1/wavs/LJ031-0082.wav|From a medical viewpoint, President Kennedy was alive when he arrived at Parkland Hospital;
LJSpeech-1.1/wavs/LJ032-0270.wav|Having reviewed the evidence that (one) Lee Harvey Oswald purchased the rifle used in the assassination,
LJSpeech-1.1/wavs/LJ024-0109.wav|Now they are making a last stand.
LJSpeech-1.1/wavs/LJ023-0087.wav|the majority of the Court has been assuming the power to pass on the wisdom of these acts of the Congress
LJSpeech-1.1/wavs/LJ043-0115.wav|He lost his job on July nineteen, nineteen sixty-three, because his work was not satisfactory
LJSpeech-1.1/wavs/LJ010-0037.wav|Now and again there seemed to be a recurrence of a murder epidemic,
LJSpeech-1.1/wavs/LJ035-0045.wav|Baker said, quote, He [Truly] had already started around the bend to come to the next elevator going up,
LJSpeech-1.1/wavs/LJ013-0099.wav|A smart detective, Forrester, after a little inquiry,
LJSpeech-1.1/wavs/LJ050-0046.wav|it has obtained the services of outside consultants, such as the Rand Corporation,
LJSpeech-1.1/wavs/LJ032-0035.wav|In addition to the order coupon the envelope contained a. U.S. postal money order for twenty-one dollars, forty-five cents,
LJSpeech-1.1/wavs/LJ033-0162.wav|from the shipping room of the Depository and forwarded it to the FBI Laboratory in Washington.
LJSpeech-1.1/wavs/LJ029-0141.wav|from Main across Elm to the access road to Stemmons Freeway and the Dallas-Fort Worth Turnpike.
LJSpeech-1.1/wavs/LJ019-0127.wav|or the still more costly process of walling in the whole farm, would have greatly added to the charges of these establishments.
LJSpeech-1.1/wavs/LJ032-0013.wav|and killing Patrolman Tippit,
LJSpeech-1.1/wavs/LJ007-0069.wav|While admitting that he had had many difficulties to contend with,
LJSpeech-1.1/wavs/LJ049-0006.wav|These precautions included reserving a ceremonial area for the Presidential party,
LJSpeech-1.1/wavs/LJ029-0169.wav|so that crowds can get a good view of President Kennedy and his wife.
LJSpeech-1.1/wavs/LJ011-0205.wav|he carried me away by fraud and stratagem, and forced me to accompany him to Gretna Green
LJSpeech-1.1/wavs/LJ039-0170.wav|and eight point two five seconds respectively.
LJSpeech-1.1/wavs/LJ015-0048.wav|But worse than the bankruptcy was the confession made by the partners in the court.
LJSpeech-1.1/wavs/LJ046-0052.wav|To promote nationwide acceptance of his administration Washington made grand tours that served also to excite interest in the Presidency.
LJSpeech-1.1/wavs/LJ033-0058.wav|On the day of the assassination, Marina Oswald was watching television when she learned of the shooting.
LJSpeech-1.1/wavs/LJ046-0240.wav|Bouck explained the failure to try to identify the individuals involved in the Stevenson incident after it occurred on the ground that
LJSpeech-1.1/wavs/LJ008-0003.wav|which we left at the time of the discontinuance of the long-practiced procession to Tyburn.
LJSpeech-1.1/wavs/LJ015-0020.wav|he was a man esteemed and respected in society and the world of finance, incapable as it was thought of a dishonest deed.
LJSpeech-1.1/wavs/LJ049-0058.wav|Secondly, agents are instructed to remove the President as quickly as possible from known or impending danger.
LJSpeech-1.1/wavs/LJ050-0207.wav|Although Chief Rowley does not complain about the pay scale for Secret Service agents,
LJSpeech-1.1/wavs/LJ011-0222.wav|He also wrote and published a pamphlet from the jail to show that Miss Turner had been a consenting party to the marriage, and was really his wife.
LJSpeech-1.1/wavs/LJ045-0085.wav|Why don't you make some money? Poor guy was going out of his mind. We told her she should not annoy him -- poor guy, he is doing his best, "Don't annoy him so much."
LJSpeech-1.1/wavs/LJ009-0154.wav|Mr. Charles Kean the tragedian was also present,
LJSpeech-1.1/wavs/LJ002-0016.wav|Previous to that date there had been seven hundred or eight hundred frequently, and once, in Mr. Akerman's time, one thousand.
LJSpeech-1.1/wavs/LJ008-0118.wav|"Thank you, sir," said the governor to the doctor, "it is of little moment."
LJSpeech-1.1/wavs/LJ006-0142.wav|The matron deposed to having seen the gates-woman "exceedingly drunk," and having been insulted by her.
LJSpeech-1.1/wavs/LJ008-0155.wav|Very great excitement prevailed in the town throughout the trial, and this greatly increased when the verdict was known.
LJSpeech-1.1/wavs/LJ003-0153.wav|Idleness was not so universally the rule in this part of the jail.
LJSpeech-1.1/wavs/LJ027-0062.wav|viz., the brain; and also usually, but not always, a number of posterior joints,
LJSpeech-1.1/wavs/LJ010-0028.wav|The causes also continued much the same. Passion, revenge, cupidity, sudden ebullitions of homicidal rage,
LJSpeech-1.1/wavs/LJ019-0183.wav|provided it was henceforth used only for untried prisoners, suggested that Newgate should be entirely reconstructed, and the new building adopted as a model.
LJSpeech-1.1/wavs/LJ015-0160.wav|he patronized the best tailors, and had a fashionable coiffeur from Hanover Square daily to curl his hair.
LJSpeech-1.1/wavs/LJ008-0313.wav|who in solemn tones communicated to each in turn the fate in store for him.
LJSpeech-1.1/wavs/LJ020-0053.wav|in the form of turnovers, pinching the corners of the fold pretty hard to hinder the flap of dough from flying up as the rising proceeds.
LJSpeech-1.1/wavs/LJ024-0026.wav|and the rules of many of our universities and of almost every great private business enterprise,
LJSpeech-1.1/wavs/LJ026-0046.wav|In each the life is the sum total of a series of definite processes -- nutrition or food supply,
LJSpeech-1.1/wavs/LJ049-0165.wav|which first appeared in the appropriation of the Department of Justice in nineteen ten under the heading, quote, Miscellaneous Objects, end quote.
LJSpeech-1.1/wavs/LJ039-0077.wav|Well, in order to achieve three hits, it would not be required that a man be an exceptional shot. A proficient man with this weapon, yes, end quote.
LJSpeech-1.1/wavs/LJ048-0219.wav|who must concentrate primarily on the possibility of threats from crowds along the route, provide a significant safeguard against dangers in nearby buildings.
LJSpeech-1.1/wavs/LJ018-0135.wav|and in the states known as "water-leaf" and "sized," which are the penultimate processes of manufacture.
LJSpeech-1.1/wavs/LJ014-0057.wav|London did not escape the contagion, and prominent among the detestable crimes of the period stands that of the Mannings at Bermondsey.
LJSpeech-1.1/wavs/LJ040-0220.wav|could have led anyone to predict the outburst of violence which finally occurred.
LJSpeech-1.1/wavs/LJ013-0037.wav|The crime of fraudulent insurance they declared was very common, and the underwriters must have lost great sums in this way.
LJSpeech-1.1/wavs/LJ050-0231.wav|Before the assassination the Secret Service infrequently requested other Federal law enforcement agencies to provide personnel
LJSpeech-1.1/wavs/LJ011-0170.wav|Wakefield, in reply to her inquiries, satisfied her that her mother was well, and that the real reason for summoning her from school
LJSpeech-1.1/wavs/LJ007-0161.wav|drink, gaming, obscene and blasphemous language; utter idleness, the almost unrestricted admission of money and luxuries;
LJSpeech-1.1/wavs/LJ010-0149.wav|She was seized before she could do any mischief,
LJSpeech-1.1/wavs/LJ002-0100.wav|A recent reform had closed the tap kept by the jailer within the precincts, but
LJSpeech-1.1/wavs/LJ048-0020.wav|The interview with him in jail is not significant from the standpoint of whether he had a propensity for violence.
LJSpeech-1.1/wavs/LJ004-0165.wav|the visitors were furnished with candles, and they descended eighteen long steps into a vault.
LJSpeech-1.1/wavs/LJ021-0070.wav|Employed workers have not by any means all enjoyed a return to the earnings of prosperous times,
LJSpeech-1.1/wavs/LJ011-0202.wav|The uncle claimed her. The husband resisted.
LJSpeech-1.1/wavs/LJ019-0268.wav|In some places the dietary was too full, in others too meager. Its constituents were not of the most suitable character.
LJSpeech-1.1/wavs/LJ048-0043.wav|nor was there any requirement to report the names of defectors. However, there was much material in the hands of the FBI about Oswald:
LJSpeech-1.1/wavs/LJ012-0254.wav|where a workman found a bundle containing two human legs, in a drain.
LJSpeech-1.1/wavs/LJ011-0084.wav|After three years' confinement in the latter prison he passed himself off as his brother, Colonel Montgomery,
LJSpeech-1.1/wavs/LJ001-0154.wav|the result as measured by the eye being that the lower margin is less than the top one, and that the whole opening has an upside-down look vertically
LJSpeech-1.1/wavs/LJ036-0058.wav|People on the bus began talking about it. As the bus neared Lamar Street, Oswald left the bus and disappeared into the crowd.
LJSpeech-1.1/wavs/LJ007-0028.wav|there still remained one where the general callous indifference and mismanagement culminated in cruel culpable neglect.
LJSpeech-1.1/wavs/LJ048-0221.wav|In the early morning hours on November twenty-two, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ004-0139.wav|"In the morning the stench and heat were so oppressive that he and every one else on waking rushed unclothed into the yard;"
LJSpeech-1.1/wavs/LJ016-0360.wav|The change added greatly to the responsibilities of the governor and his subordinates. Hitherto the public had seemed to assist at the ceremony;
LJSpeech-1.1/wavs/LJ027-0143.wav|whereby the primitive horn was gradually superseded by horns presenting a greater and greater number of prongs in successive species of extinct deer.
LJSpeech-1.1/wavs/LJ043-0159.wav|Answer: Yes.
LJSpeech-1.1/wavs/LJ005-0027.wav|He was altogether against too liberal a diet; he disapproved of industrial occupations in jails, as not calculated to render prisons terrible.
LJSpeech-1.1/wavs/LJ020-0033.wav|It will not swell so fast as the white, so give yourself more time for making it.
LJSpeech-1.1/wavs/LJ028-0194.wav|But how did the "mighty city" fall? How could Cyrus take Babylon whose walls were strong enough to resist any army?
LJSpeech-1.1/wavs/LJ017-0081.wav|sought about for a fresh victim to supply him with funds.
LJSpeech-1.1/wavs/LJ028-0443.wav|because great masses of masonry used to project from its surface.
LJSpeech-1.1/wavs/LJ019-0297.wav|The prisoners inter-communicated freely, and exercised the most injurious, corrupting influences upon one another.
LJSpeech-1.1/wavs/LJ035-0189.wav|Special Agent Forrest V. Sorrels of the Secret Service, who had been in the motorcade,
LJSpeech-1.1/wavs/LJ012-0265.wav|A woman named Gale, who lived with him, was arrested at the same time. The prisoners were examined at the Marylebone police court.
LJSpeech-1.1/wavs/LJ041-0072.wav|that he was a man of great ability and intelligence and that many of his superiors in the Marine Corps were not sufficiently competent to give him orders.
LJSpeech-1.1/wavs/LJ030-0034.wav|Approximately ten minutes after the arrival at Love Field, the President and Mrs. Kennedy went to the Presidential automobile to begin the motorcade.
LJSpeech-1.1/wavs/LJ003-0349.wav|Why not relieve Newgate by drawing more largely upon the superior accommodation which Millbank offered?
LJSpeech-1.1/wavs/LJ040-0173.wav|He always felt like a burden that she simply just had to tolerate, end quote.
LJSpeech-1.1/wavs/LJ036-0145.wav|However, Neches and Beckley do not intersect.
LJSpeech-1.1/wavs/LJ014-0152.wav|On reaching the condemned cell she threw herself upon the floor and shrieked in an hysterical agony of tears.
LJSpeech-1.1/wavs/LJ015-0263.wav|Scarcely had the conviction of these daring and astute thieves been assured, than another gigantic fraud was brought to light.
LJSpeech-1.1/wavs/LJ019-0254.wav|they were frequently below the standard size, and were therefore not certified for occupation as was required by law.
LJSpeech-1.1/wavs/LJ030-0192.wav|What are they doing to you! end quote. Looking back from the front seat,
LJSpeech-1.1/wavs/LJ007-0003.wav|and Mrs. Fry with her colleagues still labored assiduously in Newgate, devoting themselves mainly to the female prison,
LJSpeech-1.1/wavs/LJ046-0248.wav|to Federal intelligence and law enforcement agencies were not well designed to elicit information from them
LJSpeech-1.1/wavs/LJ048-0025.wav|and had told Mrs. Paine that when he got the money he was going to take an apartment, when the baby was old enough, he was going to take an apartment, and the family would live together.
LJSpeech-1.1/wavs/LJ044-0235.wav|If there was no conspiracy which would help him escape, the possibility of which has been considered in chapter six,
LJSpeech-1.1/wavs/LJ026-0049.wav|In turn these will be compared for the animal and the plant,
LJSpeech-1.1/wavs/LJ040-0051.wav|While there is doubt about how fully Oswald understood the doctrine which he so often espoused, it seems clear
LJSpeech-1.1/wavs/LJ016-0109.wav|but not till they had had an exciting chase down the street.
LJSpeech-1.1/wavs/LJ003-0092.wav|There were frequently in the middle yard seven or eight children, the youngest barely nine,
LJSpeech-1.1/wavs/LJ028-0074.wav|But in Babylonia stone was difficult to obtain, and sculptures were very rare.
LJSpeech-1.1/wavs/LJ033-0108.wav|In deciding whether Oswald carried the assassination weapon in the bag which Frazier and Mrs. Randle saw,
LJSpeech-1.1/wavs/LJ047-0083.wav|The Passport Office of the Department of State in Washington had no listing for Oswald requiring special treatment,
LJSpeech-1.1/wavs/LJ022-0108.wav|For many months preparations have been under way.
LJSpeech-1.1/wavs/LJ008-0064.wav|When the criminals are tied up and prepared for their fate, this floor suddenly falls down, upon withdrawing the supporters inwards.
LJSpeech-1.1/wavs/LJ034-0141.wav|and he said that the shots came from inside the building, end quote.
LJSpeech-1.1/wavs/LJ015-0216.wav|This was an important step, and they might easily be robbed some day when Burgess was the guard, provided only that they could be opened.
LJSpeech-1.1/wavs/LJ047-0007.wav|It had interviewed him twice shortly after his return to the United States, again a year later at his request
LJSpeech-1.1/wavs/LJ002-0190.wav|The best, or at least the most influential prisoners, got lodging in the State House, which contained "eight large handsome rooms."
LJSpeech-1.1/wavs/LJ031-0083.wav|the doctors observed that he had a heartbeat and was making some respiratory efforts.
LJSpeech-1.1/wavs/LJ044-0196.wav|to a country in which he must have thought were embodied the political principles to which he had been committed for so long.
LJSpeech-1.1/wavs/LJ009-0017.wav|For this the chaplain was a few days later summoned before the jail committee of aldermen,
LJSpeech-1.1/wavs/LJ004-0057.wav|For the first time the doctrine was enunciated that prisoners had rights of their own.
LJSpeech-1.1/wavs/LJ005-0126.wav|Religious worship became more generally the rule; chaplains were appointed, and chapels provided for them; surgeons and hospitals also.
LJSpeech-1.1/wavs/LJ036-0025.wav|McWatters was sure that he left the checkpoint on time
LJSpeech-1.1/wavs/LJ022-0152.wav|There is likewise pending before the Congress
LJSpeech-1.1/wavs/LJ002-0142.wav|These courts were open to many and grave objections.
LJSpeech-1.1/wavs/LJ034-0165.wav|Lee Harvey Oswald.
LJSpeech-1.1/wavs/LJ040-0130.wav|and interviewed and observed by other members of the Youth House staff.
LJSpeech-1.1/wavs/LJ044-0114.wav|he received a letter from somebody in New York, some Communist -- probably from New York -- I am not sure from where -- from some Communist leader and he was very happy,
LJSpeech-1.1/wavs/LJ031-0212.wav|The body was muscular and well developed with no gross skeletal abnormalities except for those caused by the gunshot wounds.
LJSpeech-1.1/wavs/LJ016-0041.wav|and working with his hands behind him, while he used his bare feet like claws upon the other side of the wall angle.
LJSpeech-1.1/wavs/LJ005-0173.wav|I shall not hesitate to ask Parliament for powers to compel them to make the necessary alterations, for it is not to be endured that these local jurisdictions should remain
LJSpeech-1.1/wavs/LJ014-0332.wav|Cole escaped by throwing the blame on a careless partner, and at once removed the "stop."
LJSpeech-1.1/wavs/LJ010-0143.wav|This axe is still in existence, and is preserved at Newgate with various other unpleasant curiosities,
LJSpeech-1.1/wavs/LJ035-0066.wav|In an effort to determine whether Oswald could have descended to the lunchroom
LJSpeech-1.1/wavs/LJ016-0335.wav|There was no interference with the crowd, which collected as usual, although not to the customary extent.
LJSpeech-1.1/wavs/LJ029-0067.wav|nor did PRS develop any additional information between November twelve, when Lawson left Washington, and November twenty-two.
LJSpeech-1.1/wavs/LJ048-0115.wav|to determine what matters require attention in making advance preparations and to decide what action to take.
LJSpeech-1.1/wavs/LJ005-0183.wav|All that was urged was that the borough magistracy had no right to govern their jails
LJSpeech-1.1/wavs/LJ014-0134.wav|that O'Connor had been more to her than her husband, that she ought to have married him.
LJSpeech-1.1/wavs/LJ018-0093.wav|As a blind for their new frauds, they set up as law-stationers in York Buildings, Adelphi, and at once commenced their nefarious traffic.
LJSpeech-1.1/wavs/LJ006-0052.wav|The sum total thus produced was inconsiderable compared with the hundreds that had formerly filled the jail,
LJSpeech-1.1/wavs/LJ033-0081.wav|she looked out the breakfast-room window and saw Oswald cross the street and walk toward the driveway where her brother parked his car near the carport.
LJSpeech-1.1/wavs/LJ012-0010.wav|both having been recognized by the clergyman who had performed the ceremony, and the assault had been committed to secure the money
LJSpeech-1.1/wavs/LJ008-0267.wav|no less than four hundred and fifty-one sentences of death for capital crimes were passed at the Old Bailey;
LJSpeech-1.1/wavs/LJ025-0086.wav|and the few and exceptional cases of non-parasitic animals which do not feed at all.
LJSpeech-1.1/wavs/LJ005-0132.wav|Only a few glaring evils still demanded a remedy.
LJSpeech-1.1/wavs/LJ004-0213.wav|Compared with those highly meritorious institutions Newgate still showed but badly.
LJSpeech-1.1/wavs/LJ003-0206.wav|and their gibes and jollity counteracted the ordinary's counsels or the independent preacher's earnest prayers.
LJSpeech-1.1/wavs/LJ030-0243.wav|but I had no time to speculate as to its origin because Agent Youngblood turned in a flash, immediately after the first explosion,
LJSpeech-1.1/wavs/LJ015-0228.wav|Pierce boldly stepped in, found the cupboard unlocked; he removed the key, handed it to Agar outside,
LJSpeech-1.1/wavs/LJ032-0171.wav|and that this was the same shirt which Oswald wore on the morning of the assassination.
LJSpeech-1.1/wavs/LJ028-0418.wav|About that same time Pietro della Valle, an Italian, visited Babylon,
LJSpeech-1.1/wavs/LJ032-0074.wav|The mail-order coupon listed the purchaser as "A. J. Hidell Age twenty-eight"
LJSpeech-1.1/wavs/LJ036-0209.wav|A similar description was given on channel two at twelve:forty-five p.m.
LJSpeech-1.1/wavs/LJ009-0300.wav|Traveling expenses of these agents cost fifteen pounds, and another ten pounds were spent in the hire of a Shropshire man,
LJSpeech-1.1/wavs/LJ004-0112.wav|three. Prisoners guilty of misdemeanors. four. Prisoners charged with misdemeanors. five. Debtors.
LJSpeech-1.1/wavs/LJ036-0098.wav|William Whaley, a taxicab driver, told his employer on Saturday morning, November twenty-three
LJSpeech-1.1/wavs/LJ032-0200.wav|One Sunday, while his wife was hanging diapers, Oswald asked her to take a picture of him holding a rifle, a pistol
LJSpeech-1.1/wavs/LJ008-0174.wav|One cart-load of spectators having broken down, some of its occupants fell off the vehicle, and were instantly trampled to death.
LJSpeech-1.1/wavs/LJ006-0120.wav|by drawing briefs and petitions for his fellows. There was a recognized charge of five shillings per brief,
LJSpeech-1.1/wavs/LJ018-0264.wav|Roupell was quiet and submissive while in Newgate, unassuming in manner, and ready to make the best of his position.
LJSpeech-1.1/wavs/LJ035-0086.wav|The time actually required for Baker and Truly to reach the second floor on November twenty-two was probably longer than in the test runs. For example,
LJSpeech-1.1/wavs/LJ038-0262.wav|Robert A. Frazier, an FBI ballistics identification expert, testified that he was, quote, unable to reach a conclusion, end quote,
LJSpeech-1.1/wavs/LJ019-0116.wav|anticipating the best results from a system which made earnings, and indeed release, dependent upon the amount of work done.
LJSpeech-1.1/wavs/LJ046-0036.wav|regarding certain protective measures in force at the time of the Dallas trip and propose recommendations for improvements.
LJSpeech-1.1/wavs/LJ033-0094.wav|As they sat in the car, Frazier asked Oswald where his lunch was, and Oswald replied that he was going to buy his lunch that day.
LJSpeech-1.1/wavs/LJ042-0027.wav|In addition to studying the Russian language while he was in the Marines,
LJSpeech-1.1/wavs/LJ006-0140.wav|Evidence was given before the inspectors of eight or ten prisoners seen "giddy drunk, not able to sit upon forms."
LJSpeech-1.1/wavs/LJ012-0138.wav|They also ascertained that a gold-refiner,
LJSpeech-1.1/wavs/LJ013-0207.wav|In this he gave as the motives of his crime a quarrel he had with his master, who threatened to discharge him without a character.
LJSpeech-1.1/wavs/LJ011-0032.wav|declared that they had hitherto formed a high opinion of his honor, integrity, and goodness of disposition,
LJSpeech-1.1/wavs/LJ019-0369.wav|In the same way, six months' notice was required in cases where the closing of a prison was contemplated;
LJSpeech-1.1/wavs/LJ016-0384.wav|when the first shock of the verdict and the solemn notification of the impending blow keeps nearly all awake, or at least disturbs their night's rest.
LJSpeech-1.1/wavs/LJ014-0034.wav|Hocker, whose skill in counterfeiting handwriting was known, was asked to fabricate a letter making an assignation with Delarue
LJSpeech-1.1/wavs/LJ003-0006.wav|Besides this, although the families of debtors were no longer permitted to live with them inside the jail,
LJSpeech-1.1/wavs/LJ043-0149.wav|where she had gone, contrary to his instructions, after she became, worried about his absence.
LJSpeech-1.1/wavs/LJ012-0006.wav|A watch was set on him at her house, where he was soon afterwards arrested.
LJSpeech-1.1/wavs/LJ042-0105.wav|he took the position that the Communist Party officials in the Soviet Union were opportunists who were betraying their positions for personal gain.
LJSpeech-1.1/wavs/LJ005-0219.wav|female prisoners were still exposed to the full view of the males, the netting in front of the gallery being perfectly useless as a screen.
LJSpeech-1.1/wavs/LJ040-0212.wav|The factors in Lee Oswald's personality which were noted by those who had contact with him in New York indicate
LJSpeech-1.1/wavs/LJ042-0205.wav|There can be no sympathy for those who have turned the idea of communism into a vile curse to Western man.
LJSpeech-1.1/wavs/LJ006-0066.wav|In the middle yard it was still worse.
LJSpeech-1.1/wavs/LJ003-0124.wav|He was charged with moving something which should not be touched, with leaving a door open, or coughing maliciously to the disturbance of his companions.
LJSpeech-1.1/wavs/LJ038-0009.wav|When he heard police sirens, he, quote, looked up and saw the man enter the lobby, end quote.
LJSpeech-1.1/wavs/LJ015-0303.wav|but on being searched, two blank cheques of the London and Westminster Bank were found in his pocket.
LJSpeech-1.1/wavs/LJ028-0373.wav|The Hebrew exiles, whose ancestors Nebuchadnezzar had brought from Jerusalem,
LJSpeech-1.1/wavs/LJ009-0183.wav|the site of the present Sessions House of the Old Bailey, and the operation was witnessed by students and a number of curious spectators.
LJSpeech-1.1/wavs/LJ044-0111.wav|for anybody who is concerned about developments in Cuba, end quote,
LJSpeech-1.1/wavs/LJ031-0065.wav|As a result of the infusion of liquids through the cutdowns, the cardiac massage, and the airway,
LJSpeech-1.1/wavs/LJ035-0139.wav|They reentered the building by the rear door several minutes after Baker and Truly rushed through the front entrance.
LJSpeech-1.1/wavs/LJ041-0105.wav|led to an incident in which he spilled a drink on one of his sergeants and abusively challenged him to fight.
LJSpeech-1.1/wavs/LJ050-0182.wav|Liaison With Local Law Enforcement Agencies
LJSpeech-1.1/wavs/LJ009-0198.wav|and her body publicly exhibited in a place built for the purpose in the Old Bailey.
LJSpeech-1.1/wavs/LJ004-0085.wav|As far back as the reign of Charles the second, a law was passed declaring that sufficient provision should be made for the relief and setting on work
LJSpeech-1.1/wavs/LJ027-0032.wav|Internal organs may persist unchanged and hence they offer good guides to classification.
LJSpeech-1.1/wavs/LJ026-0010.wav|Since they cannot be classified, it is necessary that they be listed both under botany and zoology, in order to make sure that they will not be omitted entirely.
LJSpeech-1.1/wavs/LJ009-0117.wav|The firmest disbeliever in religion, if he had not lately been irritated by taking part in such a scene as the condemned service in Newgate,
LJSpeech-1.1/wavs/LJ012-0272.wav|They were apparently good friends when last seen together at a neighbor's, where they seemed "perfectly happy and sociable, and eager for the wedding day."
LJSpeech-1.1/wavs/LJ005-0110.wav|and so passing by the roof down into the garden and on to freedom.
LJSpeech-1.1/wavs/LJ027-0096.wav|as, indeed, she must be according to the derivation theory.
LJSpeech-1.1/wavs/LJ038-0025.wav|Patrolman M. N. McDonald, with Patrolmen R. Hawkins, T. A. Hutson, and C. T. Walker, entered the theatre from the rear.
LJSpeech-1.1/wavs/LJ029-0202.wav|the president of the Dallas Chamber of Commerce referred to the city's reputation for being the friendliest town in America and asserted that citizens would, quote,
LJSpeech-1.1/wavs/LJ003-0044.wav|The reforms which were to be attempted in that prison
LJSpeech-1.1/wavs/LJ032-0146.wav|Latona testified that this palmprint was the right palmprint of Lee Harvey Oswald.
LJSpeech-1.1/wavs/LJ046-0219.wav|The above action should be taken without delay in order to attempt to verify the information and no evaluation of the information should be attempted.
LJSpeech-1.1/wavs/LJ015-0155.wav|that so good a man had really been for years a swindler and a rogue.
LJSpeech-1.1/wavs/LJ015-0307.wav|The evidence was corroborated by that of many of the victims who had acted as messengers,
LJSpeech-1.1/wavs/LJ023-0093.wav|Chief Justice Hughes said in a dissenting opinion that the majority opinion was "a departure from sound principles,"
LJSpeech-1.1/wavs/LJ009-0111.wav|the condemned returning to the cells: the forger carried by turnkeys; the youth sobbing aloud convulsively, as a passionate child;
LJSpeech-1.1/wavs/LJ039-0100.wav|During the first week of an intensive eight-week training period he received instruction in sighting, aiming, and manipulation of the trigger.
LJSpeech-1.1/wavs/LJ047-0150.wav|West Fifth Street, Irving, Texas. After receiving this information on October twenty-nine, Agent Hosty attempted to locate Oswald.
LJSpeech-1.1/wavs/LJ034-0037.wav|Someone sitting on the box facing the window would have his palm in this position if he placed his hand alongside his right hip.
LJSpeech-1.1/wavs/LJ048-0008.wav|was his attempt on General Walker's life, which did not become known to the FBI until after the assassination.
LJSpeech-1.1/wavs/LJ043-0061.wav|at the time of his defection, when he evidenced no interest in his father and hardly mentioned him, even when questioned.
LJSpeech-1.1/wavs/LJ026-0107.wav|Dissolved in water, the sugar is transported down delicate tubes, chiefly in the growing bark region of the stem.
LJSpeech-1.1/wavs/LJ048-0242.wav|Three members of this shift separately took this opportunity to visit the Cellar Coffee House.
LJSpeech-1.1/wavs/LJ012-0104.wav|The thieves were satisfied with the diamonds; they broke open other cases containing gold watches and plate, but abstracted nothing.
LJSpeech-1.1/wavs/LJ003-0173.wav|He continued the ancient practice of letting out a portion of his own house, and by a poetical fiction treated it as an annex of the state side.
LJSpeech-1.1/wavs/LJ037-0221.wav|He was wearing a zipper jacket which he had not been wearing moments before when he had arrived home.
LJSpeech-1.1/wavs/LJ048-0201.wav|I stressed the fact that this was our President and he should be shown every respect due his position and that it was our duty to see that this was done.
LJSpeech-1.1/wavs/LJ003-0237.wav|The fees on reception and discharge must be deemed exorbitant, when it is remembered the impoverished class who usually crowded the jail;
LJSpeech-1.1/wavs/LJ017-0092.wav|He decided to use strychnia, or the vegetable poison otherwise known as nux vomica;
LJSpeech-1.1/wavs/LJ042-0190.wav|democratic socializing of production, and without regard to the twisting apart of Marxism Marxist Communism by other powers.
LJSpeech-1.1/wavs/LJ018-0027.wav|In little more than a week a cabman came forward and voluntarily made a statement which at once drew suspicion to a German, Franz Müller,
LJSpeech-1.1/wavs/LJ001-0169.wav|The paper used for printing the small highly ornamented French service-books about the beginning of the sixteenth century is a model in this respect,
LJSpeech-1.1/wavs/LJ016-0202.wav|Calcraft's emoluments were a guinea per week, and an extra guinea for every execution.
LJSpeech-1.1/wavs/LJ047-0186.wav|I can now afford to wait until New Orleans forwarded the necessary papers to me to show me I now had all the information.
LJSpeech-1.1/wavs/LJ026-0070.wav|Of the substances the solids (salts, etc.) must be dissolved in water before they can be taken in.
LJSpeech-1.1/wavs/LJ008-0140.wav|Whenever the public attention had been specially called to a particular crime, either on account of its atrocity,
LJSpeech-1.1/wavs/LJ038-0115.wav|At the first interrogation, Oswald claimed that his only crime was carrying a gun and resisting arrest.
LJSpeech-1.1/wavs/LJ028-0511.wav|Should you walk along the shore of the Euphrates at Babylon, you would still see the embankments which Nebuchadnezzar constructed of bricks bearing his name,
LJSpeech-1.1/wavs/LJ011-0228.wav|Mr. W. Wakefield served in a continental army, and rose to the rank of colonel,
LJSpeech-1.1/wavs/LJ028-0005.wav|Leaving the city by the eastern gate, and passing a small village or two,
LJSpeech-1.1/wavs/LJ025-0007.wav|so much so as to require discussion in different treatises.
LJSpeech-1.1/wavs/LJ001-0033.wav|but which must certainly have come from the study of the twelfth or even the eleventh century MSS.
LJSpeech-1.1/wavs/LJ026-0166.wav|back to starch usable as food and the comparison of the green plant and the animal would be complete.
LJSpeech-1.1/wavs/LJ007-0113.wav|were revived for the convenience of these gentlemen, whose incarceration was thus rendered as little like imprisonment as possible.
LJSpeech-1.1/wavs/LJ006-0284.wav|It was a special evil of this part of the prison, that the devotional exercises, originally so profitable, had grown into a kind of edifying spectacle,
LJSpeech-1.1/wavs/LJ018-0329.wav|their crimes follow in the lines of others already found, and often more than once, in the calendars.
LJSpeech-1.1/wavs/LJ039-0187.wav|In fact, one of the firers in the rapid fire test in firing his two series of three shots,
LJSpeech-1.1/wavs/LJ050-0170.wav|This matter is obviously beyond the jurisdiction of the Commission,
LJSpeech-1.1/wavs/LJ003-0081.wav|Persons convicted of publishing libels were still immured in the same rooms with transports and felons.
LJSpeech-1.1/wavs/LJ046-0082.wav|must depend upon the utmost cooperation and understanding from the public and the President.
LJSpeech-1.1/wavs/LJ010-0174.wav|About six p.m. the royal carriage, a low open vehicle drawn by four horses, ridden by postilions, left the palace.
LJSpeech-1.1/wavs/LJ014-0041.wav|Such an extravagant defense did not weigh with judge or jury;
LJSpeech-1.1/wavs/LJ050-0266.wav|The exchange of letters dated August thirty-one, nineteen sixty-four,
LJSpeech-1.1/wavs/LJ045-0187.wav|There is, of course, no way to determine the degree to which he was committed to his plan at that time.
LJSpeech-1.1/wavs/LJ014-0106.wav|The lime had done its work so rapidly that the features would have been indistinguishable but for the prominent chin and a set of false teeth.
LJSpeech-1.1/wavs/LJ038-0117.wav|He falsely alleged that he bought the revolver in Fort Worth, when in fact he purchased it from a mail-order house in Los Angeles.
LJSpeech-1.1/wavs/LJ034-0127.wav|Brennan testified that they were standing, which is their apparent position in the photograph.
LJSpeech-1.1/wavs/LJ030-0163.wav|Mrs. John F. Kennedy, on the left of the rear seat of the limousine, looked toward her left and waved to the crowds along the route.
LJSpeech-1.1/wavs/LJ005-0245.wav|This committee animadverted strongly upon the system in force at the metropolitan jails, and more especially upon the condition of Newgate
LJSpeech-1.1/wavs/LJ038-0202.wav|Prior to the Walker shooting on April ten, Oswald had been attending typing classes on Monday, Tuesday, and Thursday evenings.
LJSpeech-1.1/wavs/LJ015-0302.wav|who was at length taken in a coffee-shop near Oxford Street, under the name of Hopkins. He resisted at first, and denied his identity,
LJSpeech-1.1/wavs/LJ036-0013.wav|found along the path of flight taken by the gunman from the scene of the shooting to the place of arrest.
LJSpeech-1.1/wavs/LJ026-0004.wav|Yet there are many unicellular forms in which both kinds of nutrition go on at the same time;
LJSpeech-1.1/wavs/LJ014-0282.wav|There were two counts in the indictment: one for stealing a cheque value fourteen hundred pounds, the second for stealing a bit of paper value one penny.
LJSpeech-1.1/wavs/LJ016-0160.wav|The noose was one of his hammock straps, which he buckled round his throat.
LJSpeech-1.1/wavs/LJ007-0164.wav|forbid the faintest shadow of a hope that in a soil so unfavorable for moral culture
LJSpeech-1.1/wavs/LJ041-0119.wav|stating that he would, quote, employ all means to right this gross mistake or injustice, end quote.
LJSpeech-1.1/wavs/LJ044-0090.wav|I think that we finished him on that program because we had publicly linked the Fair Play for Cuba Committee
LJSpeech-1.1/wavs/LJ007-0191.wav|has been productive of at least some advantage,
LJSpeech-1.1/wavs/LJ010-0270.wav|exactly tallied with that of the deformed person "wanted" for the assault on the Queen.
LJSpeech-1.1/wavs/LJ037-0029.wav|It was Benavides, using Tippit's car radio, who first reported the killing of Patrolman Tippit at about one:sixteen p.m.:
LJSpeech-1.1/wavs/LJ009-0101.wav|move with a quick, jerking motion, not naturally, but, as it were, like the affected parts of a galvanized corpse.
LJSpeech-1.1/wavs/LJ016-0162.wav|he fastened one end of the strap above mentioned to the hook, and then fell down.
LJSpeech-1.1/wavs/LJ032-0169.wav|Having considered the probabilities as explained in Stombaugh's testimony,
LJSpeech-1.1/wavs/LJ031-0200.wav|The President then walked to the Executive Office Building, where he worked until nine p.m.
LJSpeech-1.1/wavs/LJ044-0132.wav|He had not liked his job as a greaser of coffee processing machinery and he held it for only a little over two months.
LJSpeech-1.1/wavs/LJ042-0179.wav|without defense or foundation of government, end quote,
LJSpeech-1.1/wavs/LJ018-0251.wav|He confessed himself a perjurer in having sworn to the false will, and a wholesale forger, having manufactured no less than ten false signatures
LJSpeech-1.1/wavs/LJ044-0171.wav|On September twenty, nineteen sixty-three, Mrs. Paine and her two children arrived in New Orleans from a trip to the East Coast
LJSpeech-1.1/wavs/LJ018-0001.wav|The Chronicles of Newgate, Volume two. By Arthur Griffiths. Section twenty-one: Newgate Notorieties, part two.
LJSpeech-1.1/wavs/LJ031-0013.wav|Traveling at speeds estimated at times to be up to seventy or eighty miles per hour down the Stemmons Freeway and Harry Hines Boulevard
LJSpeech-1.1/wavs/LJ006-0188.wav|The days were passed in idleness, debauchery, riotous quarreling, immoral conversation,
LJSpeech-1.1/wavs/LJ032-0105.wav|quote, I knew there was no such organization. And I know Hidell is merely an altered Fidel, and I laughed at such foolishness.
LJSpeech-1.1/wavs/LJ010-0259.wav|a deformed lad among the crowd was seen to present a pistol at Her Majesty's carriage,
LJSpeech-1.1/wavs/LJ014-0084.wav|Returning to her own home, where Manning meantime had been calmly smoking and talking to the neighbors over the basement wall,
LJSpeech-1.1/wavs/LJ037-0102.wav|He stated further that from, quote, What I saw of him, end quote, the man looked like the man in the picture.
LJSpeech-1.1/wavs/LJ001-0184.wav|all books might be at least comely and well-looking: and if to these good qualities were added really beautiful ornament and pictures,
LJSpeech-1.1/wavs/LJ012-0096.wav|At her death the diamonds were divided between her four daughters, but only half had been claimed,
LJSpeech-1.1/wavs/LJ001-0059.wav|the greater part of these Italian printers, it should be mentioned, were Germans or Frenchmen, working under the influence of Italian opinion and aims.
LJSpeech-1.1/wavs/LJ026-0083.wav|Starch, however, contains potential energy, since the molecule is relatively unstable
LJSpeech-1.1/wavs/LJ002-0321.wav|others who arrived just after the time of distribution were often forty-eight hours without food. The latter might also be six days without meat.
LJSpeech-1.1/wavs/LJ035-0073.wav|was one minute and thirty seconds.
LJSpeech-1.1/wavs/LJ028-0166.wav|The center of each division of the town is occupied by a fortress.
LJSpeech-1.1/wavs/LJ028-0209.wav|On the sixteenth day the troops of Cyrus entered Babylon without a battle.
LJSpeech-1.1/wavs/LJ011-0132.wav|except the forgery of wills and powers of attorney.
LJSpeech-1.1/wavs/LJ022-0117.wav|Our attack upon these enemies must be without stint and without discrimination.
LJSpeech-1.1/wavs/LJ019-0118.wav|and later experience has fully proved the advantage of a judicious system of gratuities for labor;
LJSpeech-1.1/wavs/LJ034-0089.wav|Oswald had not filled any of the three orders.
LJSpeech-1.1/wavs/LJ003-0114.wav|was appointed judge, and a towel tied in knots was hung on each side in imitation of a wig.
LJSpeech-1.1/wavs/LJ011-0130.wav|This was on the last day of eighteen twenty-nine. In the following session Sir Robert Peel brought in a bill to consolidate the acts relating to forgery.
LJSpeech-1.1/wavs/LJ042-0083.wav|Oswald stated, quote, I am a Marxist, end quote. He also alluded to hardships endured by his mother as a worker,
LJSpeech-1.1/wavs/LJ044-0068.wav|as a result of which he was, quote, flooded with callers and invitations to debates, etc. as well as people interested in joining the F.P.C.C.
LJSpeech-1.1/wavs/LJ026-0129.wav|Sooner or later the starch grains are changed into a kind of sugar (glucose), which, unlike starch, dissolves in the sap
LJSpeech-1.1/wavs/LJ014-0309.wav|Few realized that these mysterious operations were the "convulsive attempt" of a ruined and dishonest speculator to sustain his credit.
LJSpeech-1.1/wavs/LJ032-0224.wav|One of the photographs taken by Marina Oswald was widely published in newspapers and magazines,
LJSpeech-1.1/wavs/LJ026-0126.wav|as a preliminary to the real processes of nutrition.
LJSpeech-1.1/wavs/LJ035-0140.wav|On entering, Lovelady saw a girl on the first floor who he believes was Victoria Adams.
LJSpeech-1.1/wavs/LJ038-0054.wav|He added that one officer grabbed the muzzle of a shotgun, drew back, and hit Oswald with the butt end of the gun in the back.
LJSpeech-1.1/wavs/LJ012-0117.wav|By-and-by the occupant of the room noticed something glittering in the center of the fire, which, to inspect more closely, he took out with the tongs.
LJSpeech-1.1/wavs/LJ006-0308.wav|The governor sent down wine on festive occasions, of which no doubt the prisoner housemaid had her share.
LJSpeech-1.1/wavs/LJ037-0021.wav|Scoggins stated that he thought he had seen a picture of Oswald in the newspapers prior to the lineup identification on Saturday.
LJSpeech-1.1/wavs/LJ031-0194.wav|At five:fifty-eight p.m. Eastern Standard Time,
LJSpeech-1.1/wavs/LJ016-0154.wav|When a bit of rope carefully secreted,
LJSpeech-1.1/wavs/LJ003-0151.wav|All who could scrape together the cash seem to have gladly availed themselves of the privilege of entering the master's side.
LJSpeech-1.1/wavs/LJ038-0175.wav|Until December three, nineteen sixty-three, the Walker shooting remained unsolved.
LJSpeech-1.1/wavs/LJ045-0134.wav|Hosty had come to the Paine residence on November one and five, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ013-0066.wav|By this means her signature was obtained; a forged will was prepared bequeathing the unclaimed stock to Miss Slack;
LJSpeech-1.1/wavs/LJ013-0185.wav|Three days later a close search of the butler's pantry produced fresh circumstantial evidence.
LJSpeech-1.1/wavs/LJ047-0109.wav|When Quigley returned to his office, he learned
LJSpeech-1.1/wavs/LJ021-0204.wav|of regulating only to meet concrete needs -- a practice of courageous recognition of change.
LJSpeech-1.1/wavs/LJ049-0191.wav|is properly manned and equipped to carry on extensive information gathering functions within the United States.
LJSpeech-1.1/wavs/LJ003-0135.wav|She went up to the ward and found him lying down, quote,
LJSpeech-1.1/wavs/LJ023-0106.wav|that something in the Constitution has compelled them regretfully to thwart the will of the people.
LJSpeech-1.1/wavs/LJ006-0282.wav|the pump was the only provision, and this in a place within sight of visitors, of the windows of the male turnkeys, and unprotected from the weather.
LJSpeech-1.1/wavs/LJ026-0143.wav|Probably foods containing carbon, hydrogen and oxygen are the sources of energy in the higher plants as in animals.
LJSpeech-1.1/wavs/LJ011-0178.wav|But another bank had since failed, and nothing could save Mr. Turner but the transfer of some property to Miss Turner, and its settlement on her,
LJSpeech-1.1/wavs/LJ016-0310.wav|Another distinguished witness feared
LJSpeech-1.1/wavs/LJ049-0203.wav|So circumscribed, it could not maintain the esprit de corps or the necessary alertness for this unique and challenging responsibility.
LJSpeech-1.1/wavs/LJ032-0272.wav|(three) fibers found on the rifle most probably came from the shirt Oswald was wearing on the day of the assassination,
LJSpeech-1.1/wavs/LJ048-0171.wav|it was not practical to select a route where the President could not be seen from roofs or windows of buildings.
LJSpeech-1.1/wavs/LJ044-0076.wav|Oswald's statements suggest that he hoped to be flooded with callers and invitations to debate.
LJSpeech-1.1/wavs/LJ032-0147.wav|At the request of the Commission, Arthur Mandella,
LJSpeech-1.1/wavs/LJ004-0222.wav|Meat was no longer issued raw, to be imperfectly cooked before a ward fire and bolted gluttonously, the whole two pounds at one sitting.
LJSpeech-1.1/wavs/LJ035-0072.wav|On the first test, the elapsed time between the simulated first shot and Baker's arrival on the second-floor stair landing
LJSpeech-1.1/wavs/LJ012-0173.wav|The event which he styles calamitous we may well characterize as one of the most deliberately atrocious murders on record.
LJSpeech-1.1/wavs/LJ007-0087.wav|at Appleby for thirteen years, at Anglesea for fifteen years, at Exeter for sixteen years, and at Pembroke
LJSpeech-1.1/wavs/LJ040-0238.wav|Such a placement was postponed, however, perhaps in part at least because Lee's behavior suddenly improved.
LJSpeech-1.1/wavs/LJ019-0220.wav|the uses of Newgate were narrowed almost entirely to those of a prison of detention.
LJSpeech-1.1/wavs/LJ005-0284.wav|of more depraved and systematic criminals.
LJSpeech-1.1/wavs/LJ015-0261.wav|The whole strange story, the long incubation and the elaborate accomplishment of the plot,
LJSpeech-1.1/wavs/LJ013-0113.wav|Robberies as daring in conception as they were boldly executed were common enough.
LJSpeech-1.1/wavs/LJ028-0383.wav|and the wild beasts of the islands shall cry in their desolate houses, and dragons in their pleasant palaces.
LJSpeech-1.1/wavs/LJ015-0227.wav|Still watching and waiting for the first chance, they seized it when the clerks left the office empty for a moment.
LJSpeech-1.1/wavs/LJ036-0106.wav|You could have picked him out without identifying him by just listening to him.
LJSpeech-1.1/wavs/LJ023-0078.wav|to presume in favor of its validity until its violation of the Constitution is proved beyond all reasonable doubt.
LJSpeech-1.1/wavs/LJ023-0077.wav|by which any law is passed,
LJSpeech-1.1/wavs/LJ031-0074.wav|quote, could have easily been hidden in the blood and hair, end quote,
LJSpeech-1.1/wavs/LJ017-0063.wav|He made no distinct admissions even on the scaffold; but when the chaplain at the last moment exhorted him to confess,
LJSpeech-1.1/wavs/LJ039-0168.wav|each fired two series of three shots.
LJSpeech-1.1/wavs/LJ026-0075.wav|are dissolved by the sap in the leaves and elsewhere and thus may pass to every portion of the plant.
LJSpeech-1.1/wavs/LJ042-0229.wav|To the question of, quote, Are you a Communist? End quote, he first answered "Yes,"
LJSpeech-1.1/wavs/LJ011-0125.wav|The other and the last criminal executed for forgery in this country was one Maynard, who was convicted of a fraud upon the Custom House.
LJSpeech-1.1/wavs/LJ028-0024.wav|gazing down upon the great Euphrates winding along the valley beneath.
LJSpeech-1.1/wavs/LJ017-0076.wav|His brother was supposed to have been his next victim, upon whose life he had also effected an insurance for another thirteen thousand pounds.
LJSpeech-1.1/wavs/LJ028-0374.wav|settled there, and finally the place was abandoned to the Arabs of the desert.
LJSpeech-1.1/wavs/LJ029-0014.wav|As a political leader, the President wished to resolve the factional controversy within the Democratic Party in Texas before the election of nineteen sixty-four.
LJSpeech-1.1/wavs/LJ005-0188.wav|that the jails attached to corporate jurisdictions continue to be the fruitful sources
LJSpeech-1.1/wavs/LJ010-0045.wav|became the victim of the most cowardly and unmanly outrages, and the attempted murder of the sovereign by Oxford in eighteen forty
LJSpeech-1.1/wavs/LJ033-0088.wav|Frazier met Oswald at the kitchen door and together they walked to the car.
LJSpeech-1.1/wavs/LJ045-0034.wav|Marina Oswald attributed that to their living apart and to the imminent birth of their second child.
LJSpeech-1.1/wavs/LJ018-0315.wav|to whom it was said one hundred pounds apiece had been given down as the price of their infidelity.
LJSpeech-1.1/wavs/LJ046-0127.wav|or from the occasional investigations initiated by the Secret Service,
LJSpeech-1.1/wavs/LJ038-0211.wav|he said that he, quote, was very sorry that he had not hit him, end quote. Marina Oswald's testimony was fully supported by the note itself
LJSpeech-1.1/wavs/LJ037-0154.wav|independently examined the four cartridge cases and arrived at the same conclusion as Cunningham.
LJSpeech-1.1/wavs/LJ024-0116.wav|When the time comes for action,
LJSpeech-1.1/wavs/LJ008-0230.wav|fell with a strange unnatural sound upon the ear
LJSpeech-1.1/wavs/LJ038-0089.wav|Expert testimony before the Commission
LJSpeech-1.1/wavs/LJ008-0273.wav|At the Old Bailey almost every one capitally convicted by a jury was sentenced to be hanged.
LJSpeech-1.1/wavs/LJ028-0036.wav|But in those very early days Babylon was little more than a shrine, surrounded with mud huts and date palms.
LJSpeech-1.1/wavs/LJ005-0235.wav|Last, and worst of all, the arrangements for keeping the condemned prisoners between sentence and execution were more than unsatisfactory.
LJSpeech-1.1/wavs/LJ046-0202.wav|The head of PRS testified that the Secret Service requested other agencies to provide, quote,
LJSpeech-1.1/wavs/LJ047-0147.wav|The Department of State did not advise either the CIA or the FBI of these facts.
LJSpeech-1.1/wavs/LJ018-0088.wav|I propose next to describe the leading features of the most important of these.
LJSpeech-1.1/wavs/LJ027-0011.wav|It is, moreover, true that all living forms are but series of modifications and extensions of one single plan of structure.
LJSpeech-1.1/wavs/LJ036-0059.wav|The Marsalis bus which Oswald boarded traveled a route west on Elm,
LJSpeech-1.1/wavs/LJ006-0131.wav|and, if he chose, pass in, all provisions, money, clothes, and letters brought for prisoners by their friends.
LJSpeech-1.1/wavs/LJ019-0111.wav|healthful, easily learnt, and well adapted to the circumstances of unskilled laborers.
LJSpeech-1.1/wavs/LJ015-0222.wav|in such a way that Tester had possession of this key for a time.
LJSpeech-1.1/wavs/LJ024-0007.wav|with the approval, as required by the Constitution, of the Senate of the United States.
LJSpeech-1.1/wavs/LJ013-0228.wav|In the pocket of the coat Mr. Cope, the governor, found a neatly-folded cloth, and asked what it was for.
LJSpeech-1.1/wavs/LJ002-0300.wav|Numerous tyrannies were practiced on all who would not and could not pay the garnish.
LJSpeech-1.1/wavs/LJ029-0151.wav|No arrangements were made for police or building custodians
LJSpeech-1.1/wavs/LJ016-0296.wav|The actual execution made some impression.
LJSpeech-1.1/wavs/LJ033-0158.wav|The palmprint was found on the closed end of the bag.
LJSpeech-1.1/wavs/LJ041-0030.wav|One of his fellow employees, Palmer McBride, stated that Oswald said he would like to kill President Eisenhower because he was exploiting the working class.
LJSpeech-1.1/wavs/LJ020-0075.wav|Into a second hollow pour the yeast and knead thoroughly for fifteen minutes.
LJSpeech-1.1/wavs/LJ017-0216.wav|there were also a Frenchman, a Norwegian (the carpenter), three Chinamen, a "Sclavonian," and a black on board.
LJSpeech-1.1/wavs/LJ044-0174.wav|and possibly to Philadelphia to look for work.
LJSpeech-1.1/wavs/LJ050-0252.wav|The occasional use of personnel from other Federal agencies to assist in protecting the President has a further advantage. It symbolizes the reality
LJSpeech-1.1/wavs/LJ013-0242.wav|This increased when the officer, accompanied by two others, a neighbor and a bailiff, entered one of the stables.
LJSpeech-1.1/wavs/LJ031-0103.wav|While Dr. Carrico went on to attend the President, Dr. Dulany stayed with the Governor and was soon joined by several other doctors.
LJSpeech-1.1/wavs/LJ029-0154.wav|and Secret Service agents riding in the motorcade.
LJSpeech-1.1/wavs/LJ006-0053.wav|and the whole by proper management might have been so accommodated as to prevent overcrowding.
LJSpeech-1.1/wavs/LJ011-0034.wav|These arguments availed little with the jury, who after a short deliberation found Fauntleroy guilty, and he was sentenced to death.
LJSpeech-1.1/wavs/LJ028-0300.wav|as it is, I kept my own counsel, and so accomplished my plans.
LJSpeech-1.1/wavs/LJ019-0379.wav|matters went on after the eighteen sixty-five Act much the same as they had done before. Districts differed greatly in the attention they paid to prison affairs.
LJSpeech-1.1/wavs/LJ004-0180.wav|a price which in those days fluctuated enormously -- as much as a hundred percent in a couple of years;
LJSpeech-1.1/wavs/LJ008-0256.wav|and with blanched cheek, and sinking, we turned away from the scene.
LJSpeech-1.1/wavs/LJ050-0115.wav|This is especially necessary with regard to the FBI and CIA,
LJSpeech-1.1/wavs/LJ009-0200.wav|were publicly exposed in a stable in Little Bridge Street, near Apothecaries' Hall,
LJSpeech-1.1/wavs/LJ019-0231.wav|and by the following year forty-seven new cells had been built on the most approved plan.
LJSpeech-1.1/wavs/LJ046-0010.wav|when his temporary residence, Blair House, was attacked by Puerto Rican Nationalists.
LJSpeech-1.1/wavs/LJ018-0157.wav|In the course of his remarks, however, he said,
LJSpeech-1.1/wavs/LJ028-0208.wav|Nabonidus fled.
LJSpeech-1.1/wavs/LJ020-0046.wav|Close the dough over it, dust your hands and kneading-board with flour and work in the shortening until the dough is elastic and ceases to be sticky.
LJSpeech-1.1/wavs/LJ044-0026.wav|Marina Oswald said she signed that name, apparently chosen because it rhymed with "Fidel,"
LJSpeech-1.1/wavs/LJ013-0002.wav|As the century advanced crimes of fraud increased.
LJSpeech-1.1/wavs/LJ043-0150.wav|She indicated that she had no advance knowledge of Oswald's plans,
LJSpeech-1.1/wavs/LJ025-0156.wav|with atmospheric air containing its ordinary minute dose of carbonic acid and with nothing else but sunlight and heat.
LJSpeech-1.1/wavs/LJ018-0286.wav|and Austin Bidwell opened a bona fide credit in the Burlington or West End branch of the Bank of England,
LJSpeech-1.1/wavs/LJ040-0180.wav|The Human Figure Drawings are empty, poor characterizations of persons approximately the same age as the subject.
LJSpeech-1.1/wavs/LJ047-0001.wav|Report of the President's Commission on the Assassination of President Kennedy. The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
LJSpeech-1.1/wavs/LJ038-0072.wav|who had driven from the theatre with Oswald.
LJSpeech-1.1/wavs/LJ029-0012.wav|He had made only a few brief visits to the State since the nineteen sixty Presidential campaign and in nineteen sixty-two he began to consider a formal visit.
LJSpeech-1.1/wavs/LJ012-0259.wav|who had been missing since the previous Christmas Day.
LJSpeech-1.1/wavs/LJ034-0084.wav|became apparent on December two, nineteen sixty-three, when an employee, Frankie Kaiser,
LJSpeech-1.1/wavs/LJ048-0184.wav|Levels of risk can be determined, however, as has been confirmed by building surveys made since the assassination for the Department of the Treasury.
LJSpeech-1.1/wavs/LJ027-0087.wav|to be entirely different machines, made each for its own purposes, at once, out of hand.
LJSpeech-1.1/wavs/LJ026-0100.wav|In the plant the inorganic matter in water from the soil are absorbed by the roots and carried up definite tubes in the woody part of the stem.
LJSpeech-1.1/wavs/LJ008-0032.wav|a scaffold was erected in front of that prison for the execution of several convicts named by the Recorder.
LJSpeech-1.1/wavs/LJ002-0124.wav|Quite half of the foregoing writs and arrests applied to sums under thirty pounds.
LJSpeech-1.1/wavs/LJ019-0159.wav|were constructed on the landings, ensconced in which warders spent the night, on duty, and alert to watch the sleepers below,
LJSpeech-1.1/wavs/LJ034-0108.wav|man in his early thirties, fair complexion, slender, but neat, neat slender, possible five foot ten
LJSpeech-1.1/wavs/LJ017-0179.wav|In all cases the symptoms were much the same,
LJSpeech-1.1/wavs/LJ028-0428.wav|has been removed, and the surrounding city walls have been traced.
LJSpeech-1.1/wavs/LJ048-0070.wav|reflect keen awareness of the necessity of communicating a much wider range of intelligence information to the Service.
LJSpeech-1.1/wavs/LJ035-0094.wav|the Commission concluded that Oswald could have fired the shots and still have been present in the second-floor lunchroom when seen by Baker and Truly.
LJSpeech-1.1/wavs/LJ013-0248.wav|At the same time an overpowering odor attracted them to the adjoining harness-room, where the missing remains were raked out
LJSpeech-1.1/wavs/LJ008-0269.wav|Already the severity of our criminal code, and the number of capital felonies upon the statute book, had brought a reaction;
LJSpeech-1.1/wavs/LJ027-0117.wav|"Now, here again the former theory appears to be triumphant over the latter," says Romanes,
LJSpeech-1.1/wavs/LJ024-0043.wav|that I will appoint justices who will not undertake to override the judgment of the Congress on legislative policy,
LJSpeech-1.1/wavs/LJ020-0059.wav|When the time is up and the rolls are puffy and promising, set them in a pretty quick oven and bake half an hour,
LJSpeech-1.1/wavs/LJ048-0049.wav|possessed of this information to list Oswald as a potential threat to the safety of the President.
LJSpeech-1.1/wavs/LJ048-0177.wav|that such a procedure would not be consistent with the nature and purpose of the motorcade to let the people see their President and to welcome him to their city.
LJSpeech-1.1/wavs/LJ007-0056.wav|leaden hearts, and "grinding the impressions off penny-pieces, then pricking figures or words on them to give to their friends as memorials.
LJSpeech-1.1/wavs/LJ032-0059.wav|Experts on handwriting identification from the Treasury Department and the FBI
LJSpeech-1.1/wavs/LJ015-0097.wav|and he could not produce them. His chief asked sternly where they were.
LJSpeech-1.1/wavs/LJ036-0130.wav|Whaley described the ensuing events as follows, quote,
LJSpeech-1.1/wavs/LJ012-0060.wav|to let the coach change and pass Petticoat Lane en route to the jail, where the suffering woman might be handed over to her friends.
LJSpeech-1.1/wavs/LJ027-0033.wav|On the other hand, external structures are likely to undergo adaptation when habits or conditions of life change.
LJSpeech-1.1/wavs/LJ047-0141.wav|in early October of nineteen sixty-three.
LJSpeech-1.1/wavs/LJ047-0219.wav|Quote, Mr. Shanklin advised us, among other things,
LJSpeech-1.1/wavs/LJ024-0004.wav|It is simply this: whenever a judge or justice of any federal court
LJSpeech-1.1/wavs/LJ003-0103.wav|It was that of a person, quote, who practiced in the law, and who was connected by marriage with some very respectable families.
LJSpeech-1.1/wavs/LJ016-0256.wav|It was thought that capital punishment would lose its deterrent effect if it ceased to be public,
LJSpeech-1.1/wavs/LJ047-0164.wav|At this point in the interview, Hosty gave Mrs. Paine his name and office telephone number on a piece of paper.
LJSpeech-1.1/wavs/LJ033-0179.wav|since the original bag had been discolored during various laboratory examinations and could not be used for valid identification by witnesses.
LJSpeech-1.1/wavs/LJ019-0071.wav|moreover, it was nearly impossible to prevent communication and mutual contamination.
LJSpeech-1.1/wavs/LJ041-0125.wav|Mrs. Oswald said that her husband did not say anything about Governor Connally after his return to the United States. She testified, quote,
LJSpeech-1.1/wavs/LJ001-0141.wav|The general solidity of a page is much to be sought for
LJSpeech-1.1/wavs/LJ004-0242.wav|Some attempt was made to reduce the overcrowding, on the recommendation of the House of Commons Committee of eighteen eighteen, but this applied only a partial remedy.
LJSpeech-1.1/wavs/LJ022-0114.wav|Our responsibility is to all of the people in this country.
LJSpeech-1.1/wavs/LJ048-0152.wav|At some overpasses all persons were excluded
LJSpeech-1.1/wavs/LJ044-0173.wav|While Marina Oswald knew of her husband's plan to go to Mexico and thence to Cuba if possible, Mrs. Paine was told that Oswald was going to Houston
LJSpeech-1.1/wavs/LJ018-0342.wav|It was to effect the rupture of an irksome tie that led Henry Wainwright to murder Harriet Lane deliberately and in cold blood.
LJSpeech-1.1/wavs/LJ004-0101.wav|Warm and cold baths, or "commodious bathing tubs,"
LJSpeech-1.1/wavs/LJ031-0090.wav|A thorough inspection would have involved washing and cleansing the back, and this is not practical in treating an acutely injured patient.
LJSpeech-1.1/wavs/LJ047-0018.wav|for the purpose of correlating information inasmuch as he was considered a possible security risk in the event he returned to this country, end quote.
LJSpeech-1.1/wavs/LJ010-0070.wav|followed the profession of arms, first in the British service, and then in that of the French revolutionary Government.
LJSpeech-1.1/wavs/LJ008-0090.wav|It was still the custom to offer warm encouragement or bitter disapproval, according to the character and antecedents of the sufferer.
LJSpeech-1.1/wavs/LJ025-0153.wav|and inquire whether certain differences of a more occult character than those imagined to exist by Cuvier,
LJSpeech-1.1/wavs/LJ048-0036.wav|that agents of the FBI in Dallas did not consider Oswald's presence in the Texas School Book Depository Building
LJSpeech-1.1/wavs/LJ008-0145.wav|They were accused by a confederate, who, goaded by conscience, had turned approver, of the murder of a Mr. Steele,
LJSpeech-1.1/wavs/LJ048-0150.wav|while the Secret Service representatives in Dallas
LJSpeech-1.1/wavs/LJ021-0117.wav|to the great number of small employers in the smaller communities.
LJSpeech-1.1/wavs/LJ006-0277.wav|But there were evils akin to those on the male side, prominent amongst which was the undue influence accorded to prisoners.
LJSpeech-1.1/wavs/LJ049-0075.wav|Recommendations.
LJSpeech-1.1/wavs/LJ010-0209.wav|Louis and Amadeus among the captains; and Hercules, Neptune, and Mars among the lieutenants of the association.
LJSpeech-1.1/wavs/LJ048-0080.wav|to coordinate activities and to discuss problems of mutual interest.
LJSpeech-1.1/wavs/LJ036-0160.wav|He also stated he saw a silver identification bracelet on his passenger's left wrist.
LJSpeech-1.1/wavs/LJ040-0090.wav|Pic did turn over part of his income to his mother,
LJSpeech-1.1/wavs/LJ015-0277.wav|When he could get nothing but the blank cheque, he set in motion all sorts of schemes for obtaining signatures, such as
LJSpeech-1.1/wavs/LJ046-0120.wav|the security processing of gifts sent to the President, and technical inspections against covert listening devices.
LJSpeech-1.1/wavs/LJ006-0029.wav|The second inspector, the Rev. Whitworth Russell, was the chaplain of Millbank penitentiary,
LJSpeech-1.1/wavs/LJ049-0153.wav|The Secret Service was organized as a division of the Department of the Treasury in eighteen sixty-five, to deal with counterfeiting.
LJSpeech-1.1/wavs/LJ041-0019.wav|Voebel said that Oswald, quote, wouldn't start any fights, but if you wanted to start one with him, he was going to make sure that he ended it,
LJSpeech-1.1/wavs/LJ018-0115.wav|It was stated in evidence that the monies obtained by these forgeries amounted to eight thousand pounds or ten thousand pounds,
LJSpeech-1.1/wavs/LJ049-0079.wav|Many changes have already been made and others are contemplated, some of them in response to the Commission's questions and informal suggestions.
LJSpeech-1.1/wavs/LJ036-0096.wav|because of the overwhelming evidence that Oswald was far away from the building by that time.
LJSpeech-1.1/wavs/LJ009-0103.wav|The silence is short. As the ordinary proceeds 'to conclude,'
LJSpeech-1.1/wavs/LJ018-0106.wav|He was a German named Kerp,
LJSpeech-1.1/wavs/LJ039-0116.wav|he had just completed a very intensive preliminary training period.
LJSpeech-1.1/wavs/LJ045-0113.wav|he did not want his landlady to know his real name because she might read in the paper of the fact that he had been in Russia and that he had been questioned, end quote.
LJSpeech-1.1/wavs/LJ014-0196.wav|by his identification by Cope in Westminster Hospital, who survived long enough to make a formal deposition before Mr. Jardine,
LJSpeech-1.1/wavs/LJ046-0124.wav|or with undue persistence.
LJSpeech-1.1/wavs/LJ012-0292.wav|Mrs. Brown fell with it, and Greenacre, to his horror, found that she was dead.
LJSpeech-1.1/wavs/LJ002-0282.wav|Those who could not pay were thrown into the wards with the night charges,
LJSpeech-1.1/wavs/LJ016-0104.wav|whence they let themselves down into the street by the rope.
LJSpeech-1.1/wavs/LJ040-0149.wav|intense anxiety, shyness, feelings of awkwardness and insecurity, end quote.
LJSpeech-1.1/wavs/LJ049-0002.wav|The Warren Commission Report. By The President's Commission on the Assassination of President Kennedy.
LJSpeech-1.1/wavs/LJ014-0242.wav|Employed as a clerk in the Globe Assurance,
LJSpeech-1.1/wavs/LJ045-0164.wav|He said that he was tired of living alone and perhaps the reason for my being so angry was the fact that we were not living together.
LJSpeech-1.1/wavs/LJ042-0155.wav|it appears to be the work of a fairly well organized person.
LJSpeech-1.1/wavs/LJ012-0011.wav|which Mrs. Canning had lost by remarriage.
LJSpeech-1.1/wavs/LJ011-0120.wav|Unfortunately he took to drink, lost his appointment, and fell from bad to worse.
LJSpeech-1.1/wavs/LJ006-0074.wav|He was unable to give any reason whatever for not utilizing the whole of the wards.
LJSpeech-1.1/wavs/LJ030-0231.wav|Most of the other Secret Service agents in the motorcade had drawn their sidearms.
LJSpeech-1.1/wavs/LJ017-0107.wav|After Cook's death his stepfather, who was much attached to him, came to Rugeley.
LJSpeech-1.1/wavs/LJ004-0219.wav|The diet was now ample. It consisted of a pound and a half of bread per diem;
LJSpeech-1.1/wavs/LJ021-0075.wav|But it is an undeniable fact that the restoration of other billions of sound investments to a reasonable earning power
LJSpeech-1.1/wavs/LJ030-0184.wav|Kellerman grabbed his microphone and radioed ahead to the lead car,
LJSpeech-1.1/wavs/LJ011-0102.wav|He had gone on board in his Quaker dress, but when captured was found in a light-green frock,
LJSpeech-1.1/wavs/LJ047-0153.wav|Having determined that Mrs. Paine was a responsible and reliable citizen, Hosty interviewed her on November one.
LJSpeech-1.1/wavs/LJ039-0241.wav|owned and possessed the rifle used to kill President Kennedy and wound Governor Connally,
LJSpeech-1.1/wavs/LJ039-0232.wav|the assassin was then required to hit the target one more time within a space of from four point eight to five point six seconds.
LJSpeech-1.1/wavs/LJ050-0149.wav|PRS must develop the capacity to classify its subjects on a more sophisticated basis than the present geographic breakdown.
LJSpeech-1.1/wavs/LJ025-0062.wav|under particular circumstances, the contents of the cells of certain water-weeds were set free and moved about with considerable velocity
LJSpeech-1.1/wavs/LJ018-0301.wav|were lodged at once by drafts to "Horton," another alias, in the Continental Bank.
LJSpeech-1.1/wavs/LJ036-0218.wav|Four bullets hit Tippit and killed him instantly.
LJSpeech-1.1/wavs/LJ024-0033.wav|and that a baneful precedent will be established.
LJSpeech-1.1/wavs/LJ040-0061.wav|Various possible motives will be treated in the appropriate context of the discussion outlined above.
LJSpeech-1.1/wavs/LJ030-0012.wav|In Houston, as elsewhere during the trip, the crowds showed much interest in Mrs. Kennedy.
LJSpeech-1.1/wavs/LJ048-0257.wav|and that their conduct the night before did not impede their actions on duty
LJSpeech-1.1/wavs/LJ011-0173.wav|Miss Turner consented to go on, and they traveled night and day towards the north.
LJSpeech-1.1/wavs/LJ011-0023.wav|A run upon the bank immediately followed, which was only met by a suspension of payment and the closing of its doors.
LJSpeech-1.1/wavs/LJ017-0235.wav|He was soon summoned on deck, but as he would not move, the mutineers came down and stood in a circle round his berth.
LJSpeech-1.1/wavs/LJ045-0086.wav|The De Mohrenschildts also testified that, quote, right in front, end quote, of Oswald Marina Oswald complained about Oswald's inadequacy as a husband.
LJSpeech-1.1/wavs/LJ036-0004.wav|After leaving the Depository Building at approximately twelve:thirty-three p.m., Lee Harvey Oswald proceeded to his roominghouse by bus and taxi.
LJSpeech-1.1/wavs/LJ036-0020.wav|The transfer was dated "Friday November twenty-two, 'sixty-three" and was punched in two places by the bus driver.
LJSpeech-1.1/wavs/LJ016-0425.wav|When visited one day in the condemned cell, just as St. Sepulchre's clock was striking, he looked up and said laughingly, "Go along, clock;
LJSpeech-1.1/wavs/LJ031-0133.wav|Jack Brooks, Homer Thornberry, and Albert Thomas joined Clifton C. Carter and the group of special agents protecting the Vice President.
LJSpeech-1.1/wavs/LJ009-0144.wav|In fact his looks denoted extreme sorrow and contrition,
LJSpeech-1.1/wavs/LJ036-0029.wav|where a man beat on the front door of the bus, boarded it and paid his fare.
LJSpeech-1.1/wavs/LJ011-0234.wav|Bigger "jobs" than ever were planned and attempted,
LJSpeech-1.1/wavs/LJ027-0145.wav|that such a recapitulation in the life history of an existing animal of developmental changes successively distinctive of sundry allied,
LJSpeech-1.1/wavs/LJ006-0291.wav|to clean the governor's office in the male prison;
LJSpeech-1.1/wavs/LJ006-0225.wav|If any man presumed to turn in too early
LJSpeech-1.1/wavs/LJ026-0037.wav|It will no doubt occur to the reader that, on the theory of evolution,
LJSpeech-1.1/wavs/LJ012-0195.wav|and of these Bishop and Williams, who were guilty of many peculiar atrocities, ended their murderous careers in front of the debtors' door at Newgate.
LJSpeech-1.1/wavs/LJ007-0135.wav|The yards were narrow and confined, mainly because the ground plan was radically vicious. These were evils inseparable from the place.
LJSpeech-1.1/wavs/LJ012-0284.wav|It was not until he left the bus, and walked up by the Regent's Canal, that he conceived the idea of throwing the head into the water.
LJSpeech-1.1/wavs/LJ025-0112.wav|With a qualification, to be considered presently, the answer to this question is undoubtedly in the affirmative.
LJSpeech-1.1/wavs/LJ029-0090.wav|were deployed in and around the Trade Mart.
LJSpeech-1.1/wavs/LJ012-0270.wav|She had realized all her effects, and brought them with her furniture to Greenacre's lodgings. The two when married were to emigrate to Hudson's Bay.
LJSpeech-1.1/wavs/LJ008-0260.wav|One of the worst evils was the terrible and long-protracted uncertainty as to the result.
LJSpeech-1.1/wavs/LJ034-0023.wav|The carton on the windowsill and the large carton below the window contained no prints which could be identified as being those of Lee Harvey Oswald.
LJSpeech-1.1/wavs/LJ007-0094.wav|had actually been returned as sane from the asylum to which they had been sent, and there was always some uncertainty as to who was mad and who not.
LJSpeech-1.1/wavs/LJ037-0205.wav|The invoice was prepared on March thirteen, nineteen sixty-three; the revolver was actually shipped on March twenty by Railway Express.
LJSpeech-1.1/wavs/LJ042-0009.wav|While his defection resulted in part from Oswald's commitment to Marxism,
LJSpeech-1.1/wavs/LJ019-0164.wav|the personal superintendence of night officers, as already described, became possible.
LJSpeech-1.1/wavs/LJ046-0011.wav|One out of every five Presidents since eighteen sixty-five has been assassinated;
LJSpeech-1.1/wavs/LJ019-0339.wav|while decency and good order were to be insured by the strict prohibition of gambling and drunkenness.
LJSpeech-1.1/wavs/LJ043-0144.wav|and the March eleven, nineteen sixty-three, issue of the Militant.
LJSpeech-1.1/wavs/LJ035-0209.wav|at twelve:thirty p.m
LJSpeech-1.1/wavs/LJ044-0048.wav|which occurred eight days after Oswald wrote the above letter to V. T. Lee.
LJSpeech-1.1/wavs/LJ022-0065.wav|The unemployment insurance part of the legislation
LJSpeech-1.1/wavs/LJ007-0193.wav|The measures of improvement introduced were mainly as follows:
LJSpeech-1.1/wavs/LJ011-0062.wav|If the law of this country can receive such a sacrifice, my death will render to heaven an innocent man, and to earth a repentant sinner.
LJSpeech-1.1/wavs/LJ008-0216.wav|until presently the huge stage loomed dark above the crowd which was now ranged round the barriers;
LJSpeech-1.1/wavs/LJ005-0190.wav|the knowledge and practice of every species of criminality.
LJSpeech-1.1/wavs/LJ030-0224.wav|heard noises that sounded like firecrackers and ran toward the President's limousine.
LJSpeech-1.1/wavs/LJ034-0043.wav|The print, therefore, could have been placed on the carton at any time within this period.
LJSpeech-1.1/wavs/LJ005-0263.wav|and not, as heretofore, to the judges of assize; that, both to check abuses and watch the progress of improvement,
LJSpeech-1.1/wavs/LJ028-0481.wav|Nabopolassar, the father, my begetter, built Imgur-Bel, the great wall of Babylon,
LJSpeech-1.1/wavs/LJ041-0144.wav|Oswald would have had other and more favorable opportunities to strike at the Governor than on this occasion when, as a member of the President's party,
LJSpeech-1.1/wavs/LJ031-0089.wav|considerable time which at this juncture was not available.
LJSpeech-1.1/wavs/LJ008-0106.wav|He was introduced by the ordinary, Dr. Forde, a name familiar to the reader, who met him at the felons' door
LJSpeech-1.1/wavs/LJ012-0066.wav|and begged his wife to send him over a consignment of cheap "righteous" watches, or such as had been honestly obtained, and not "on the cross."
LJSpeech-1.1/wavs/LJ036-0129.wav|The man asked, quote, May I have the cab?, end quote, and got into the front seat.
LJSpeech-1.1/wavs/LJ030-0025.wav|when Air Force One touched down at Love Field at eleven:forty a.m., Eastern Standard Time.
LJSpeech-1.1/wavs/LJ011-0207.wav|whom I never saw until I was taken from Liverpool, and never want to see again.
LJSpeech-1.1/wavs/LJ010-0254.wav|At the Italian Opera in the evening the audience, on the Queen's appearance, greeted her with loud cheers, and called for the national anthem.
LJSpeech-1.1/wavs/LJ001-0107.wav|To say a few words on the principles of design in typography:
LJSpeech-1.1/wavs/LJ021-0063.wav|Benefits of the Industrial Recovery Program have come,
LJSpeech-1.1/wavs/LJ029-0070.wav|is discussed in chapter eight.
LJSpeech-1.1/wavs/LJ047-0243.wav|According to Revill, Hosty indicated that he was going to tell this to Lieutenant Wells of the homicide and robbery bureau.
LJSpeech-1.1/wavs/LJ017-0146.wav|He had all the characteristics of the poisoner -- the calm deliberation,
LJSpeech-1.1/wavs/LJ021-0148.wav|may be determined and any later adjustments shall be made either by agreement or, in case of disagreement,
LJSpeech-1.1/wavs/LJ040-0131.wav|Marguerite Oswald visited her son at Youth House, where she recalled that she waited in line, quote,
LJSpeech-1.1/wavs/LJ022-0047.wav|However, for the first time in five years the relief rolls have declined instead of increased during the winter months.
LJSpeech-1.1/wavs/LJ029-0050.wav|A check of the geographic indexes there revealed no listing for any individual deemed to be a potential danger to the President
LJSpeech-1.1/wavs/LJ033-0076.wav|On the morning of November twenty-two, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ047-0233.wav|his lies to Agent Quigley, his recent visit to Mexico City -- indicated that Oswald was capable of violence.
LJSpeech-1.1/wavs/LJ050-0190.wav|However, the instructions must be communicated to the local police in any event and can be leaked to the press whether or not they are in writing.
LJSpeech-1.1/wavs/LJ031-0135.wav|Concern that the Vice President might also be a target for assassination prompted the Secret Service agents to urge him to leave the hospital and return to Washington immediately.
LJSpeech-1.1/wavs/LJ002-0009.wav|On the twenty-seventh April, in the following year,
LJSpeech-1.1/wavs/LJ015-0265.wav|was the prime mover,
LJSpeech-1.1/wavs/LJ026-0132.wav|after absorption into the cells the elements of the starch (or glucose) are, by the living protoplasm, in some unknown way
LJSpeech-1.1/wavs/LJ032-0258.wav|Ruth and Michael Paine both noticed the rolled-up blanket in the garage during the time that Marina Oswald was living in their home.
LJSpeech-1.1/wavs/LJ048-0005.wav|There was nothing up to the time of the assassination that gave any indication that this man was a dangerous character who might do harm to the President
LJSpeech-1.1/wavs/LJ006-0234.wav|More cruel injuries were common enough, which did not result from honest hand-to-hand fights.
LJSpeech-1.1/wavs/LJ019-0252.wav|while its rigid maintenance was in its opinion vital to the efficiency of the jails.
LJSpeech-1.1/wavs/LJ015-0251.wav|The latter was ere long arrested on a charge of uttering forged cheques, convicted, and sentenced to transportation for life.
LJSpeech-1.1/wavs/LJ010-0110.wav|Several of the other prisoners took the same line as regards Edwards,
LJSpeech-1.1/wavs/LJ032-0227.wav|Shaneyfelt testified that the published photographs appeared to be based on a copy of the original which the publications had each retouched differently.
LJSpeech-1.1/wavs/LJ033-0121.wav|The distance between the point on the seat and the door was twenty-seven inches.
LJSpeech-1.1/wavs/LJ041-0168.wav|even though Oswald seemed to be lost in his own thoughts. After a brief period of silence Oswald remarked on the stupidity of the parade
LJSpeech-1.1/wavs/LJ004-0086.wav|of "poor and needy prisoners committed to the common jail for felony and other misdemeanors, who many times perish before their trial;
LJSpeech-1.1/wavs/LJ022-0148.wav|to enforce minimum wages, to prevent excessive hours,
LJSpeech-1.1/wavs/LJ034-0137.wav|The two men, Harold Norman and James Jarman, Jr., each confirmed that when they came out of the building,
LJSpeech-1.1/wavs/LJ007-0221.wav|The reports as the years flow on reiterate the same complaints.
LJSpeech-1.1/wavs/LJ018-0033.wav|Directly the foregoing facts were established, a couple of detective officers, armed with a warrant to arrest Müller,
LJSpeech-1.1/wavs/LJ016-0119.wav|Under superior orders all the doors and gates of this block were left open at night, to allow the night watchman to pass freely to all parts.
LJSpeech-1.1/wavs/LJ019-0104.wav|That gentleman had come to the conclusion that the ordinary and hackneyed methods of treatment were practically inefficacious,
LJSpeech-1.1/wavs/LJ011-0145.wav|The new Forgery Act with the Lords' amendment passed into law, but the latter proved perfectly harmless,
LJSpeech-1.1/wavs/LJ003-0069.wav|In this heterogeneous society were also thrown the unfortunate journalists to whom I have already referred, and on whom imprisonment in Newgate
LJSpeech-1.1/wavs/LJ038-0091.wav|The Commission has, therefore, placed no reliance on the paraffin tests administered by the Dallas police.
LJSpeech-1.1/wavs/LJ018-0034.wav|and accompanied by Mr. Death the jeweler and the cabman, went down to Liverpool and took the first steamer across the Atlantic.
LJSpeech-1.1/wavs/LJ013-0167.wav|The discovery of the murdered man immediately followed. The neighborhood was alarmed, the police sent for, and a close inquiry forthwith commenced.
LJSpeech-1.1/wavs/LJ025-0021.wav|yet none of these movements justify the ascription to plants of perception of will.
LJSpeech-1.1/wavs/LJ033-0214.wav|(four) carried the rifle into the Depository Building, concealed in the bag;
LJSpeech-1.1/wavs/LJ017-0159.wav|and a life-interest in five thousand pounds, a fact on which Smethurst's counsel dwelt with much weight,
LJSpeech-1.1/wavs/LJ042-0063.wav|with few readily available alternatives at hand. He was shocked to find that the Soviet Union did not accept him with open arms.
LJSpeech-1.1/wavs/LJ028-0159.wav|thence from the corners of the wall there is carried along each bank of the river a fence of burned bricks.
LJSpeech-1.1/wavs/LJ036-0193.wav|Description of Shooting
LJSpeech-1.1/wavs/LJ027-0099.wav|Another striking class of the facts of morphology which admit of scientific explanation only along the line of homology
LJSpeech-1.1/wavs/LJ050-0003.wav|By The President's Commission on the Assassination of President Kennedy. Chapter eight. The Protection of the President. Part five.
LJSpeech-1.1/wavs/LJ017-0166.wav|but was careful to prime them with his facts and lead them if possible to accept his diagnosis of the case.
LJSpeech-1.1/wavs/LJ005-0282.wav|"the comparatively innocent are seduced, the unwary are entrapped,
LJSpeech-1.1/wavs/LJ005-0150.wav|In some county jails, as I have already said, female prisoners were placed upon the tread-wheel;
LJSpeech-1.1/wavs/LJ016-0032.wav|Williams as a capital convict was lodged in the press-yard or condemned ward.
LJSpeech-1.1/wavs/LJ028-0221.wav|When I made my gracious entry into Babylon, with exceeding joy I took up my abode in the royal palace.
LJSpeech-1.1/wavs/LJ050-0134.wav|that an interagency committee has been established to develop more effective criteria.
LJSpeech-1.1/wavs/LJ010-0078.wav|On his second release, goaded by his fancied wrongs, he began to plot a dark and dreadful revenge,
LJSpeech-1.1/wavs/LJ011-0223.wav|Neither his address nor his pamphlet availed much, for the bill for the divorce passed both Houses.
LJSpeech-1.1/wavs/LJ002-0186.wav|The population generally amounted to from five hundred to seven hundred, the accommodation being calculated for two hundred.
LJSpeech-1.1/wavs/LJ022-0164.wav|It will put the public utility operating industry on a sound basis for the future,
LJSpeech-1.1/wavs/LJ034-0183.wav|Boxes and cases were stacked behind him.
LJSpeech-1.1/wavs/LJ013-0079.wav|when Lord Campbell delivered judgment on Barber's petition, to the effect that
LJSpeech-1.1/wavs/LJ033-0101.wav|so that it was carried straight and parallel to his body.
LJSpeech-1.1/wavs/LJ038-0289.wav|As shown above, the note and the photographs of Walker's house and of the nearby railroad tracks
LJSpeech-1.1/wavs/LJ047-0136.wav|they had vacated their apartment, and Marina Oswald had departed with their child in a station wagon with Texas registration.
LJSpeech-1.1/wavs/LJ033-0097.wav|Frazier parked the car in the company parking lot about two blocks north of the Depository Building.
LJSpeech-1.1/wavs/LJ045-0250.wav|there emerged a man capable of assassinating President Kennedy.
LJSpeech-1.1/wavs/LJ016-0353.wav|Almost absolute silence prevailed until the great bell began to toll its deep note, and broke the stillness with its regular and monotonous clangour,
LJSpeech-1.1/wavs/LJ019-0053.wav|and our modern practice has prudently tried to steer between the two extremes, accepting as the best system a judicious combination of both.
LJSpeech-1.1/wavs/LJ013-0012.wav|Her owners insured her for a full sum of two thousand pounds, after which the Wallaces insured her privily
LJSpeech-1.1/wavs/LJ016-0157.wav|One curious instance of a suicide carried out under the most adverse and extraordinary circumstances may be quoted.
LJSpeech-1.1/wavs/LJ038-0169.wav|he saw two men, in separate cars, drive out of a church parking lot adjacent to Walker's home. A friend of Walker's testified that
LJSpeech-1.1/wavs/LJ029-0071.wav|An important purpose of the President's visit to Dallas was to speak at a luncheon given by business and civic leaders.
LJSpeech-1.1/wavs/LJ007-0117.wav|where the upper ward was exclusively appropriated to their use. They also had their meals sent in, and, with the food, wine almost ad libitum.
LJSpeech-1.1/wavs/LJ033-0092.wav|the main reason he was going over there that Thursday afternoon when he was to bring back some curtain rods, so I didn't think any more about it when he told me that, end quote,
LJSpeech-1.1/wavs/LJ045-0076.wav|The letter fell into Oswald's hands when it was returned to his post office box
LJSpeech-1.1/wavs/LJ049-0152.wav|The assignment of the responsibility of protecting the President to an agency of the Department of the Treasury was largely an historical accident.
LJSpeech-1.1/wavs/LJ013-0029.wav|Even then she might have been saved, but the captain would not suffer the crew to act. Nearly the whole of the cargo was lost as well as the ship.
LJSpeech-1.1/wavs/LJ030-0189.wav|he realized that something was wrong, and he pressed down on the accelerator as Kellerman said, quote, Get out of here fast, end quote.
LJSpeech-1.1/wavs/LJ004-0166.wav|At the bottom was a circular space, through which ran a narrow passage, and the sides of which were fitted with barrack bedsteads.
LJSpeech-1.1/wavs/LJ028-0191.wav|The old enemies of Babylon rejoiced.
LJSpeech-1.1/wavs/LJ036-0166.wav|is three to four short blocks south of Lamar and Elm. If Oswald left the bus at twelve:forty-four p.m.
LJSpeech-1.1/wavs/LJ033-0057.wav|and insert it into the paper bag.
LJSpeech-1.1/wavs/LJ050-0066.wav|The volume of references to the Secret Service has increased substantially since the new instructions went into effect;
LJSpeech-1.1/wavs/LJ045-0166.wav|He repeated this not once but several times, but I refused. And he said that once again I was preferring my friends to him, and that I didn't need him.
LJSpeech-1.1/wavs/LJ007-0024.wav|who supped royally on the supplies provided from outside, and kept it up till ten or eleven o'clock.
LJSpeech-1.1/wavs/LJ036-0142.wav|Whaley was somewhat imprecise as to where he unloaded his passenger.
LJSpeech-1.1/wavs/LJ008-0044.wav|and at the distance of five feet from the same is fixed a strong railing all round the scaffold to enclose a place for the constables.
LJSpeech-1.1/wavs/LJ015-0309.wav|and the judge, in passing sentence on him of transportation for life, expressed deep regret that "the ingenuity, skill, and talent,
LJSpeech-1.1/wavs/LJ050-0272.wav|and the traditions of the office in a democracy such as ours are so deep-seated as to preclude absolute security.
LJSpeech-1.1/wavs/LJ014-0238.wav|In eighteen fifty occurred the first of a series of gigantic frauds,
LJSpeech-1.1/wavs/LJ027-0084.wav|Romanes's "Darwin and After Darwin", and Le Conte's "Evolution."
LJSpeech-1.1/wavs/LJ041-0067.wav|Other marines also testified that Oswald had few friends and kept very much to himself.
LJSpeech-1.1/wavs/LJ037-0261.wav|that the jacket belonged to Lee Harvey Oswald, and that when he was arrested at approximately one:fifty p.m., he was in shirt sleeves.
LJSpeech-1.1/wavs/LJ021-0182.wav|And let it be recorded that the British bankers helped.
LJSpeech-1.1/wavs/LJ004-0197.wav|No idleness was permitted among the inmates. Trades were taught, or prisoners were allowed to follow their own if suitable.
LJSpeech-1.1/wavs/LJ002-0065.wav|or female convicts ordered for execution.
LJSpeech-1.1/wavs/LJ050-0274.wav|made certain recommendations which it believes would, if adopted,
LJSpeech-1.1/wavs/LJ003-0146.wav|without them the keeper declared that he could not pay the salaries of turnkeys and servants, nor keep the prison going at all.
LJSpeech-1.1/wavs/LJ039-0225.wav|Based on the known facts of the assassination,
LJSpeech-1.1/wavs/LJ029-0198.wav|They conveyed the pleas of Dallas leaders that citizens not demonstrate or create disturbances during the President's visit.
LJSpeech-1.1/wavs/LJ016-0408.wav|During the singing of these hymns Wainwright fainted, but whether from real emotion or the desire to make a sensation was never exactly known.
LJSpeech-1.1/wavs/LJ038-0063.wav|but that once he was subdued, no officer struck him.
LJSpeech-1.1/wavs/LJ011-0180.wav|Wakefield added that it had been suggested he should marry Miss Turner, but that he had laughed at the idea.
LJSpeech-1.1/wavs/LJ003-0285.wav|they should gamble with dice or cards, and play at bumble puppy or some other disreputable game of chance.
LJSpeech-1.1/wavs/LJ045-0184.wav|Then on Thursday morning, November twenty-one,
LJSpeech-1.1/wavs/LJ008-0213.wav|By this time the workmen might be heard busily erecting the gallows;
LJSpeech-1.1/wavs/LJ040-0140.wav|Mrs. Evelyn D Siegel, a social worker who interviewed both Lee and his mother while Lee was confined in Youth House,
LJSpeech-1.1/wavs/LJ028-0153.wav|The bitumen used in the work was brought to Babylon from Is, a small stream which flows into the Euphrates
LJSpeech-1.1/wavs/LJ038-0168.wav|There were no eyewitnesses, although a fourteen-year-old boy in a neighboring house claimed that immediately after the shooting
LJSpeech-1.1/wavs/LJ008-0285.wav|on the one hand the gallows, on the other a short imprisonment.
LJSpeech-1.1/wavs/LJ019-0298.wav|The total want of administration was very marked,
LJSpeech-1.1/wavs/LJ028-0059.wav|His military career began while he was still the crown prince, and his father was on the throne.
LJSpeech-1.1/wavs/LJ005-0121.wav|By degrees, however,
LJSpeech-1.1/wavs/LJ015-0200.wav|only when single and unprotected were they in any danger of attack, and that but rarely.
LJSpeech-1.1/wavs/LJ014-0295.wav|This man got up to look for him, and found him hanging from the bars of a neighboring room.
LJSpeech-1.1/wavs/LJ027-0151.wav|The only alternative view is that as species of deer,
LJSpeech-1.1/wavs/LJ039-0130.wav|After reviewing Oswald's marksmanship scores,
LJSpeech-1.1/wavs/LJ022-0070.wav|Provisions for social security, however, are protections for the future.
LJSpeech-1.1/wavs/LJ044-0039.wav|they said something about remodeling, etc. I'm sure you understand, end quote.
LJSpeech-1.1/wavs/LJ049-0078.wav|have properly taken the initiative in reexamining major aspects of Presidential protection.
LJSpeech-1.1/wavs/LJ037-0004.wav|At least twelve persons saw the man with the revolver in the vicinity of the Tippit crime scene at or immediately after the shooting.
LJSpeech-1.1/wavs/LJ001-0145.wav|No definite rules, however, except the avoidance of "rivers" and excess of white, can be given for the spacing,
LJSpeech-1.1/wavs/LJ039-0230.wav|With the equipment he [Oswald] had and with his ability I consider it a very easy shot, end quote.
LJSpeech-1.1/wavs/LJ023-0112.wav|We have, therefore,
LJSpeech-1.1/wavs/LJ026-0092.wav|animals (and colorless plants as well) apparently could not long exist.
LJSpeech-1.1/wavs/LJ040-0139.wav|while he liked Youth House, he missed the freedom of doing what he wanted. He indicated that he did not miss his mother, end quote.
LJSpeech-1.1/wavs/LJ030-0191.wav|According to Kellerman, Mrs. Kennedy then cried out, quote,
LJSpeech-1.1/wavs/LJ028-0084.wav|Its impression shows the face of a beardless young man, intelligent and refined.
LJSpeech-1.1/wavs/LJ016-0394.wav|The request was not granted, as the old custom of allowing capital convicts whatever they asked for in the way of food has not been the rule in Newgate.
LJSpeech-1.1/wavs/LJ016-0376.wav|literally walked over what, in case of conviction, would be their own graves.
LJSpeech-1.1/wavs/LJ001-0062.wav|Even in Italy most of the theological and law books were printed in Gothic letter,
LJSpeech-1.1/wavs/LJ007-0234.wav|slanting downwards from the top of the walls to the outside adjoining the slaughterhouses of Newgate market; and occasionally, in hot weather,
LJSpeech-1.1/wavs/LJ028-0414.wav|All the ground on which Babylon was spread is left now desolate; nothing standing in that Peninsula between the Euphrates and the Tigris,
LJSpeech-1.1/wavs/LJ044-0044.wav|to an attack by Cuban exiles in a street demonstration and being, quote, officialy cautioned, end quote, by the police.
LJSpeech-1.1/wavs/LJ032-0222.wav|Moreover, Shaneyfelt testified that in his opinion the photographs were not composites of two different photographs
LJSpeech-1.1/wavs/LJ007-0073.wav|to that line of conduct which his duty imposed on him
LJSpeech-1.1/wavs/LJ017-0204.wav|who said that he feared it was only too true that secret poisoning was at that time very rife in the metropolis.
LJSpeech-1.1/wavs/LJ002-0313.wav|It generally ran to about six pounds per week. The money, which at one time had been distributed quarterly, and all went in drink,
LJSpeech-1.1/wavs/LJ045-0209.wav|but it was also, at least in part, because his wife did not want to live there with him.
LJSpeech-1.1/wavs/LJ003-0303.wav|The personal cleanliness of all prisoners was to be insisted upon; they should be made to wash at least once a day,
LJSpeech-1.1/wavs/LJ010-0280.wav|On June eighteen fifty the Queen was once more subjected to cowardly outrage, the offender being a Mr. Pate, a gentleman by birth,
LJSpeech-1.1/wavs/LJ011-0087.wav|Montgomery was duly sentenced to death, but he preferred suicide to the gallows. After sentence his demeanor was serious yet firm.
LJSpeech-1.1/wavs/LJ040-0071.wav|From the time Marguerite Oswald returned to work until December twenty-six, nineteen forty-two, when Lee too was sent to the orphans' home,
LJSpeech-1.1/wavs/LJ037-0104.wav|manager of a used-car lot on the northeast corner of Patton Avenue and Jefferson Boulevard, and Sam Guinyard, a porter at the lot.
LJSpeech-1.1/wavs/LJ018-0245.wav|in all good faith to another, but a criminal member of the family.
LJSpeech-1.1/wavs/LJ039-0082.wav|this is the ideal type of weapon for moving targets
LJSpeech-1.1/wavs/LJ001-0182.wav|the books so ornamented are amongst the most delightful works of art that have ever been produced.
LJSpeech-1.1/wavs/LJ007-0196.wav|the provision of dining-rooms and dining-tables.
LJSpeech-1.1/wavs/LJ002-0148.wav|and that no more than one hundred ninety-seven creditors recovered debts and costs.
LJSpeech-1.1/wavs/LJ013-0197.wav|Mr. Phillips, who led in the case, went to the other extreme,
LJSpeech-1.1/wavs/LJ040-0134.wav|that anybody entering this home had to be searched in case the parents were bringing cigarettes or narcotics or anything, end quote.
LJSpeech-1.1/wavs/LJ015-0255.wav|and begged his accomplice to invest it as a settlement on a woman named Kay, by whom he had had a child.
LJSpeech-1.1/wavs/LJ015-0141.wav|from which he rose to be assistant registrar, with the special duties of transferring shares.
LJSpeech-1.1/wavs/LJ049-0110.wav|The governmental consequences of assassination of one of the specified officials give the United States ample power to act for its own protection.
LJSpeech-1.1/wavs/LJ040-0152.wav|turning around the topics of omnipotence and power, through which he tries to compensate for his present shortcomings and frustrations, end quote.
LJSpeech-1.1/wavs/LJ009-0173.wav|from eighteen thirty-two to eighteen forty-four not a single person had been executed in the metropolis except for this the gravest crime.
LJSpeech-1.1/wavs/LJ003-0079.wav|Mr. Bennet refers to a gentleman confined for want of bail, who occupied a room with five others
LJSpeech-1.1/wavs/LJ019-0027.wav|The internal arrangements of the new model were carefully supervised by a body of distinguished men, among which were many peers, Lord John Russell,
LJSpeech-1.1/wavs/LJ048-0125.wav|the precautions taken for the President's trip were the usual safeguards employed on trips of this kind in the United States during the previous year, end quote.
LJSpeech-1.1/wavs/LJ022-0073.wav|Our problem is to put to work three and one-half million employable persons now on the relief rolls.
LJSpeech-1.1/wavs/LJ013-0105.wav|Elder, the former, was soon apprehended at his house, but he evaded the law by hanging himself with his pocket-handkerchief.
LJSpeech-1.1/wavs/LJ011-0083.wav|For a long time justice did not overtake him for any criminal offense, but he was frequently in Newgate and in the King's Bench for debt.
LJSpeech-1.1/wavs/LJ002-0041.wav|Two other wards were appropriated to the master's side debtors; they were each twenty-three feet by fourteen and a half,
LJSpeech-1.1/wavs/LJ046-0213.wav|members of his immediate family, the President-elect, and the Vice-President. Investigation of threats against the President of the United States,
LJSpeech-1.1/wavs/LJ005-0195.wav|There was no decency whatever in the internal arrangements;
LJSpeech-1.1/wavs/LJ019-0020.wav|Up to the twenty-first December, eighteen forty-two,
LJSpeech-1.1/wavs/LJ003-0161.wav|The luxury of the state side was for a long time open to all who could pay
LJSpeech-1.1/wavs/LJ050-0172.wav|The Commission, therefore, recommends that the President consider ordering an inquiry into the possibility
LJSpeech-1.1/wavs/LJ050-0089.wav|While these tentative criteria are a step in the right direction,
LJSpeech-1.1/wavs/LJ046-0098.wav|The history of Presidential protection shows growing recognition over the years that the job must be done by able, dedicated,
LJSpeech-1.1/wavs/LJ037-0074.wav|and her positive identification of Oswald at a police lineup, the Commission considers her testimony reliable.
LJSpeech-1.1/wavs/LJ033-0020.wav|prior to November twenty-one, nineteen sixty-three, except on Monday, October twenty-one, when he visited his wife in the hospital
LJSpeech-1.1/wavs/LJ019-0362.wav|Where the local authority had neglected to comply with the provisions of the eighteen sixty-five Act for four consecutive years,
LJSpeech-1.1/wavs/LJ019-0036.wav|This list included Wakefield, Leeds, Kirkdale, Manchester, Birmingham, and Dublin.
LJSpeech-1.1/wavs/LJ005-0212.wav|and the prison allowance was still limited to bread and water.
LJSpeech-1.1/wavs/LJ048-0206.wav|As the motorcade approached Elm Street
LJSpeech-1.1/wavs/LJ024-0037.wav|who would disregard the law and would decide specific cases as I wished them to be decided, I make this answer:
LJSpeech-1.1/wavs/LJ015-0063.wav|But neither Robson nor Redpath would have been able to pursue their fraudulent designs with success had they not, like Watts,
LJSpeech-1.1/wavs/LJ033-0102.wav|When Oswald entered the rear door of the Depository Building, he was about fifty feet ahead of Frazier.
LJSpeech-1.1/wavs/LJ022-0151.wav|did more than anything else to bring about the recent collapse of industries.
LJSpeech-1.1/wavs/LJ003-0054.wav|An imperfect attempt at classification was, however, made in eighteen twelve, and a yard was as far as possible set apart for the untried,
LJSpeech-1.1/wavs/LJ015-0192.wav|From the moment of his reception he gave himself great airs, as a martyr and a man heavily wronged.
LJSpeech-1.1/wavs/LJ025-0123.wav|has not only been discovered to exist far more widely among plants than was formerly imagined,
LJSpeech-1.1/wavs/LJ035-0134.wav|that they were watching the parade from the top step of the building entrance when Gloria Calverly, who works in the Depository Building,
LJSpeech-1.1/wavs/LJ014-0310.wav|Pries, although enjoying a high reputation in the city, had long been in a bad way.
LJSpeech-1.1/wavs/LJ030-0179.wav|She watched as he slumped down with an empty expression on his face.
LJSpeech-1.1/wavs/LJ008-0150.wav|Four years passed without the detection of the murderers,
LJSpeech-1.1/wavs/LJ039-0174.wav|The marksmen took as much time as they wanted for the first target and all hit the target.
LJSpeech-1.1/wavs/LJ041-0089.wav|Thornley added, quote, I think it was kind of necessary to him to believe that he was being picked on.
LJSpeech-1.1/wavs/LJ029-0207.wav|On November twenty-one there appeared on the streets of Dallas the anonymous handbill mentioned above.
LJSpeech-1.1/wavs/LJ010-0092.wav|Lord Harrowby's dinner-party was postponed, but the conspirators knew nothing of it,
LJSpeech-1.1/wavs/LJ022-0113.wav|to make a major attack upon the problem of unemployment.
LJSpeech-1.1/wavs/LJ028-0060.wav|In six oh five,
LJSpeech-1.1/wavs/LJ019-0044.wav|The south and west of England were also very laggard, and many years were still to elapse before the prisons in these parts were properly reconstituted.
LJSpeech-1.1/wavs/LJ029-0079.wav|was a one-story building with few entrances and easy to make secure, but it lacked necessary food-handling facilities
LJSpeech-1.1/wavs/LJ020-0050.wav|Toss the lump dough upon it and knead thoroughly for five minutes.
LJSpeech-1.1/wavs/LJ002-0176.wav|Neild gives a list of the various items charged upon a debt of ten pounds, which included instructions to sue,
LJSpeech-1.1/wavs/LJ005-0202.wav|An examination of this report shows how even the most insignificant township had its jail.
LJSpeech-1.1/wavs/LJ049-0019.wav|The last Presidential vehicle with any protection against small-arms fire left the White House in nineteen fifty-three.
LJSpeech-1.1/wavs/LJ011-0165.wav|who had plausibly explained that he had only recently been engaged at Shrigley.
LJSpeech-1.1/wavs/LJ039-0031.wav|Mr. Nixon advised the Commission that the only time he was in Dallas in nineteen sixty-three
LJSpeech-1.1/wavs/LJ028-0218.wav|Without a skirmish or a battle, he permitted them to enter Babylon, and, sparing the city, he delivered the King Nabonidus to him.
LJSpeech-1.1/wavs/LJ004-0163.wav|and of which fewer still would believe that the original is to be found in this enlightened and happy country."
LJSpeech-1.1/wavs/LJ037-0255.wav|testified that Commission Exhibit Number one sixty-two was the jacket worn by the man they saw on November twenty-two.
LJSpeech-1.1/wavs/LJ044-0106.wav|and Benjamin J. Davis honorary membership cards in his nonexistent New Orleans chapter of the Fair Play for Cuba Committee,
LJSpeech-1.1/wavs/LJ019-0214.wav|The Corporation owned lands there covering from nineteen to twenty acres.
LJSpeech-1.1/wavs/LJ030-0213.wav|Hill heard a second shot, proximately five seconds after the first, which removed a portion of the President's head.
LJSpeech-1.1/wavs/LJ013-0043.wav|This person made much of Wallace, encouraged his attentions to his daughter,
LJSpeech-1.1/wavs/LJ008-0013.wav|As regards the first, I find that in seventeen eighty-six
LJSpeech-1.1/wavs/LJ004-0076.wav|"Disease, cold, famine, nakedness, and contagious and polluted air are not lawful punishments in the hands of the civil magistrates;
LJSpeech-1.1/wavs/LJ040-0133.wav|She said that her pocketbook was searched, quote, because the children in this home were such criminals, dope fiends, and had been in criminal offenses,
LJSpeech-1.1/wavs/LJ048-0031.wav|While he had expressed hostility at times toward the State Department, the Marine Corps, and the FBI as agents of the Government,
LJSpeech-1.1/wavs/LJ001-0073.wav|went on apace; and by the end of the sixteenth century there was no really beautiful printing done:
LJSpeech-1.1/wavs/LJ020-0076.wav|Wrap bowl and biscuit in a thick cloth and set to rise where it will neither become chilled nor sour over night.
LJSpeech-1.1/wavs/LJ019-0166.wav|those for trial, and those sentenced for short terms or long
LJSpeech-1.1/wavs/LJ038-0097.wav|the Commission gave little weight to his denials of guilt.
LJSpeech-1.1/wavs/LJ042-0116.wav|Under the entry for May one, nineteen sixty,
LJSpeech-1.1/wavs/LJ035-0012.wav|At about this time he heard the first shot.
LJSpeech-1.1/wavs/LJ019-0102.wav|which was promptly carried, with the additional instruction to the committee to suggest any improvements.
LJSpeech-1.1/wavs/LJ003-0115.wav|The judge sat in proper form; he was punctiliously styled "my lord."
LJSpeech-1.1/wavs/LJ002-0154.wav|Thus, amongst others, Thomas Blackburn had been committed on October fifteenth for a debt of one shilling five pence.
LJSpeech-1.1/wavs/LJ048-0010.wav|stressed also the decision by the Department of State that Oswald should be permitted to return to the United States.
LJSpeech-1.1/wavs/LJ003-0309.wav|Proper hours for locking and unlocking prisoners should be insisted upon;
LJSpeech-1.1/wavs/LJ036-0032.wav|So I gave her a transfer and opened the door and she was going out the gentleman I had picked up about two blocks [back]
LJSpeech-1.1/wavs/LJ001-0177.wav|so that if the two are helpful to one another it is a mere matter of accident.
LJSpeech-1.1/wavs/LJ033-0069.wav|As she [Marina] told me about it I stepped onto the blanket roll
LJSpeech-1.1/wavs/LJ035-0172.wav|There he was met by a construction worker -- in all likelihood Howard Brennan, who was wearing his work helmet.
LJSpeech-1.1/wavs/LJ041-0057.wav|His study of Communist literature,
LJSpeech-1.1/wavs/LJ044-0208.wav|An examination of the Militant, to which Oswald subscribed,
LJSpeech-1.1/wavs/LJ036-0207.wav|The suspect was described as a, quote,
LJSpeech-1.1/wavs/LJ011-0081.wav|He was not prosecuted for this fraud on account of the respectability of his family, and soon after this escape
LJSpeech-1.1/wavs/LJ028-0229.wav|The Babylonians, encamped without their walls, awaited his coming.
LJSpeech-1.1/wavs/LJ016-0368.wav|It was they who formed the chief part of the small select group of spectators;
LJSpeech-1.1/wavs/LJ007-0011.wav|But it was already plain that they constituted an independent authority within the jails; they were frequently in conflict with the chaplain,
LJSpeech-1.1/wavs/LJ011-0250.wav|While thus engaged, Howard thrust the poker into the fire.
LJSpeech-1.1/wavs/LJ021-0180.wav|to issue new bonds therefore bearing only three and one half percent interest,
LJSpeech-1.1/wavs/LJ011-0128.wav|Maynard was convicted of uttering the forged document, Jones of being an accessory; the third prisoner was acquitted.
LJSpeech-1.1/wavs/LJ028-0469.wav|The inner wall of Babylon was called Imgur-Bel, and like the outer wall, it was double.
LJSpeech-1.1/wavs/LJ040-0030.wav|When he was in the Soviet Union, he apparently resented the Communist Party members,
LJSpeech-1.1/wavs/LJ015-0291.wav|partly through their own carelessness, when transferring their operations to Yarmouth.
LJSpeech-1.1/wavs/LJ045-0222.wav|The feelings of hostility and aggression which seem to have played such an important, part in Oswald's life
LJSpeech-1.1/wavs/LJ001-0026.wav|On the whole the type of this book may be considered the ne-plus-ultra of Gothic type,
LJSpeech-1.1/wavs/LJ024-0006.wav|a new member shall be appointed by the President then in office,
LJSpeech-1.1/wavs/LJ024-0114.wav|and who would be willing to support a reasonable amendment if they could agree on one.
LJSpeech-1.1/wavs/LJ042-0059.wav|Despite this commitment to the Soviet Union
LJSpeech-1.1/wavs/LJ013-0119.wav|Howse, the steward, accused the other servants, but they retorted, declaring that he had been visited by the thief the day previous,
LJSpeech-1.1/wavs/LJ029-0102.wav|After the selection of the Trade Mart as the luncheon site,
LJSpeech-1.1/wavs/LJ046-0002.wav|The President's Commission on the Assassination of President Kennedy. Chapter eight. The Protection of the President. Part one.
LJSpeech-1.1/wavs/LJ019-0372.wav|It was practically inoperative as regards the penalties for neglect. It was no doubt as irksome and inconvenient to the Secretary of State
LJSpeech-1.1/wavs/LJ047-0248.wav|that he ever said that Oswald was capable of violence, or that he had any information suggesting this.
LJSpeech-1.1/wavs/LJ003-0134.wav|One day he was too ill to come down and meet her.
LJSpeech-1.1/wavs/LJ005-0094.wav|to call for information as to the observance of its provisions.
LJSpeech-1.1/wavs/LJ021-0171.wav|Now that these people are coming out of their storm cellars, they forget that there ever was a storm.
LJSpeech-1.1/wavs/LJ004-0007.wav|It was so powerless against the persistent neglect of those intrusted with prison management, that, five-and-twenty years later,
LJSpeech-1.1/wavs/LJ016-0361.wav|the moment too that the condemned man had passed through the debtors' door on to the scaffold the prison had done with him,
LJSpeech-1.1/wavs/LJ019-0357.wav|The Secretary of State was empowered to deal rather summarily with "inadequate" prisons, in other words,
LJSpeech-1.1/wavs/LJ002-0163.wav|a market porter, was arrested and committed at the suit of a publican
LJSpeech-1.1/wavs/LJ049-0204.wav|While in accordance with its mandate
LJSpeech-1.1/wavs/LJ031-0121.wav|Dr. George T. Shires, assisted by Drs. Robert McClelland, Charles Baxter, and Ralph Don Patman,
LJSpeech-1.1/wavs/LJ019-0198.wav|and on a more mature consideration he realized that the limited area of the existing Newgate site,
LJSpeech-1.1/wavs/LJ011-0155.wav|He had eloped with his first wife from school.
LJSpeech-1.1/wavs/LJ015-0293.wav|as coming from a Mr. Whitney.
LJSpeech-1.1/wavs/LJ036-0206.wav|again at twelve:forty-eight p.m., and again at twelve:fifty-five p.m.
LJSpeech-1.1/wavs/LJ016-0003.wav|and that none of its inmates could hope to escape from its secure precincts.
LJSpeech-1.1/wavs/LJ020-0037.wav|The oven must be steady, but not so hot as for white bread, nor will the Graham bread be done quite so soon as that made of bolted flour.
LJSpeech-1.1/wavs/LJ028-0387.wav|The Sassanian kings of Persia were fond of hunting, and Babylon, then overgrown with trees, was their game preserve.
LJSpeech-1.1/wavs/LJ017-0168.wav|But a long public discussion followed, and in consequence he was reprieved.
LJSpeech-1.1/wavs/LJ015-0173.wav|Warrants were issued for Redpath's arrest, but he had flown to Paris.
LJSpeech-1.1/wavs/LJ006-0033.wav|The ink was barely dry upon their letters of appointment before they appeared at Newgate, and commenced a searching investigation.
LJSpeech-1.1/wavs/LJ010-0283.wav|and walking for choice through prickly gorse bushes.
LJSpeech-1.1/wavs/LJ009-0085.wav|'Now for you, my poor fellow mortals, who are about to suffer the last penalty of the law.'
LJSpeech-1.1/wavs/LJ006-0297.wav|Some member of the Ladies' Association observed and commented upon the fact that a "young rosy-cheeked girl" had been kept by the governor from transportation,
LJSpeech-1.1/wavs/LJ024-0094.wav|It would take months and years thereafter to get a two-thirds majority in favor of that amendment in both Houses of the Congress.
LJSpeech-1.1/wavs/LJ002-0092.wav|The two yards were adjoining, that for the common side much the largest.
LJSpeech-1.1/wavs/LJ008-0186.wav|The concourse was very great, notwithstanding these warnings.
LJSpeech-1.1/wavs/LJ009-0202.wav|In eighteen eleven Williams, who murdered the Marrs in Ratcliffe Highway, having committed suicide in jail to escape hanging,
LJSpeech-1.1/wavs/LJ009-0277.wav|For a second or two the body hung motionless, then, with a strength that astonished the attendant officials,
LJSpeech-1.1/wavs/LJ047-0060.wav|Fain had been assigned to see Marina Oswald at an appropriate time.
LJSpeech-1.1/wavs/LJ020-0042.wav|and these also tend to nourish and strengthen the brain.
LJSpeech-1.1/wavs/LJ034-0005.wav|He worked principally on the first and sixth floors of the building, gathering books listed on orders and delivering them to the shipping room on the first floor.
LJSpeech-1.1/wavs/LJ050-0063.wav|and who have been involved in bombing or bomb-making or whose past conduct indicates tendencies toward violence, and (d)
LJSpeech-1.1/wavs/LJ045-0081.wav|Although she denied it in some of her testimony before the Commission,
LJSpeech-1.1/wavs/LJ006-0266.wav|On these occasions precautions were supposed to be taken to exclude bad characters,
LJSpeech-1.1/wavs/LJ047-0045.wav|and promised to advise the FBI if he heard from them.
LJSpeech-1.1/wavs/LJ017-0267.wav|After condemnation, as the rules now kept capital convicts strictly apart, they could not be lodged in the two condemned cells,
LJSpeech-1.1/wavs/LJ008-0243.wav|Threading his way among these itinerant vendors was seen the meek-faced deliverer of tracts, the man of good intentions, now bonneted,
LJSpeech-1.1/wavs/LJ034-0054.wav|In addition, Mandella was of the opinion that the print taken from the carton on the floor
LJSpeech-1.1/wavs/LJ013-0216.wav|His account of his acts and movements after the deed
LJSpeech-1.1/wavs/LJ011-0233.wav|that thieves or depredators were idle or entirely unsuccessful.
LJSpeech-1.1/wavs/LJ033-0176.wav|taken from the Texas School Book Depository shipping room on November twenty-two, nineteen sixty-three.
LJSpeech-1.1/wavs/LJ028-0487.wav|Fortunately its walls have suffered less from the hands of the brick hunters, and the German excavators have been able to reconstruct their plan.
LJSpeech-1.1/wavs/LJ047-0205.wav|to potential danger, quote,
LJSpeech-1.1/wavs/LJ031-0085.wav|Since the Dallas doctors directed all their efforts to controlling the massive bleeding caused by the head wound, and to reconstructing an airway to his lungs,
LJSpeech-1.1/wavs/LJ006-0252.wav|The worst fights occurred on Sunday afternoons; but nearly every night the act of locking up became, from the consequent removal of all supervision,
LJSpeech-1.1/wavs/LJ015-0295.wav|he was told it was only at Mr. Whitney's disposal, and that it could be paid to no one else.
LJSpeech-1.1/wavs/LJ004-0169.wav|On the dirty bedstead lay a wretched being in the throes of severe illness.
LJSpeech-1.1/wavs/LJ009-0168.wav|robbery, burglary, and arson.
LJSpeech-1.1/wavs/LJ009-0148.wav|But the chaplain admitted that the solitude of the convict's cell
LJSpeech-1.1/wavs/LJ048-0187.wav|In addition, Secret Service agents riding in the motorcade were trained to scan buildings as part of their general observation of the crowd of spectators.
LJSpeech-1.1/wavs/LJ004-0141.wav|The hospital was filled with infectious cases, and in one room, seven feet by nine, with closed windows,
LJSpeech-1.1/wavs/LJ032-0153.wav|A palmprint could not be placed on this portion of the rifle, when assembled, because the wooden foregrip covers the barrel at this point.
LJSpeech-1.1/wavs/LJ019-0243.wav|and thus bring the history of prison discipline down to our own times.
LJSpeech-1.1/wavs/LJ037-0174.wav|but only two of the four discarded cartridge cases found on the lawn at tenth Street and Patton Avenue were of Winchester-Western manufacture.
LJSpeech-1.1/wavs/LJ010-0146.wav|Attacks upon the sovereign, as I have said, became more common after the accession of the young Queen Victoria in eighteen thirty-eight.
LJSpeech-1.1/wavs/LJ014-0019.wav|His name was Hocker; he was by trade a ladies' shoemaker; and it was also ascertained that after the day of the murder he was flush of money.
LJSpeech-1.1/wavs/LJ008-0105.wav|Mr. Smith's account of the condemned convict, whose cell he was permitted to enter, may be inserted here.
LJSpeech-1.1/wavs/LJ028-0317.wav|Introduced into their assembly, he began to bewail his misfortunes, telling them that
LJSpeech-1.1/wavs/LJ033-0186.wav|one cannot estimate when, prior to November twenty-two, Oswald made the paper bag.
LJSpeech-1.1/wavs/LJ035-0110.wav|Both Dougherty and Piper were confused witnesses. They had no exact memory of the events of that afternoon.
LJSpeech-1.1/wavs/LJ045-0131.wav|Neither Hosty nor any other agent of the FBI spoke to Oswald on any subject from August ten, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ012-0156.wav|His arrest and conviction cast dismay over the whole gang of receivers, and for a time seriously checked the nefarious traffic.
LJSpeech-1.1/wavs/LJ004-0130.wav|incommodious, as has been stated, insecure, unhealthy, and unprovided with the printed or written regulations required by law.
LJSpeech-1.1/wavs/LJ013-0220.wav|that Courvoisier was idle, discontented, ready to take offense, greedy of gain;
LJSpeech-1.1/wavs/LJ033-0085.wav|She then opened the kitchen door and saw Oswald open the right rear door of her brother's car and place the package in the back of the car.
LJSpeech-1.1/wavs/LJ017-0143.wav|which followed close on its heels, although in that the verdict of "Not Guilty" was excusable, as the evidence was entirely circumstantial.
LJSpeech-1.1/wavs/LJ021-0068.wav|to a level of sustained profits within one year from the inauguration of N.R.A.
LJSpeech-1.1/wavs/LJ030-0135.wav|Mrs. Connally, elated by the reception, turned to President Kennedy and said, quote, Mr. President, you can't say Dallas doesn't love you.
LJSpeech-1.1/wavs/LJ015-0045.wav|the firm's paper went down further and further in value; an application to the Committee of Bankers for assistance was peremptorily refused,
LJSpeech-1.1/wavs/LJ008-0009.wav|But the Old Bailey was not exclusively used;
LJSpeech-1.1/wavs/LJ004-0019.wav|were as yet but imperfectly understood, and such portions of the "improved" jails of that period as were still extant a few years back,
LJSpeech-1.1/wavs/LJ002-0303.wav|Besides these fees, legitimate and illegitimate, there were others which must be paid before release.
LJSpeech-1.1/wavs/LJ014-0178.wav|His offense was the murder of Richard Cope,
LJSpeech-1.1/wavs/LJ045-0089.wav|Marina Oswald also ridiculed her husband's political views, thereby tearing down his view of his own importance.
LJSpeech-1.1/wavs/LJ037-0111.wav|Guinyard and Callaway ran to tenth and Patton and found Tippit lying in the street beside his car.
LJSpeech-1.1/wavs/LJ020-0018.wav|Throw a cloth over the bowl and set by for five or six hours to rise.
LJSpeech-1.1/wavs/LJ046-0242.wav|Such an approach seriously undermines the precautionary nature of PRS work;
LJSpeech-1.1/wavs/LJ029-0161.wav|From the airport, the President's party will proceed to Mockingbird Lane to Lemmon and then to Turtle Creek, turning south to Cedar Springs.
LJSpeech-1.1/wavs/LJ050-0024.wav|toward the preparation of formal understandings of the respective roles of the Secret Service and other agencies with which it collaborates
LJSpeech-1.1/wavs/LJ013-0218.wav|His last statement contains the words, "The public now think I am a liar, and they will not believe me when I say the truth."
LJSpeech-1.1/wavs/LJ015-0029.wav|In December eighteen fifty-one the balance sheet showed a deficiency of upwards of seventy thousand pounds.
LJSpeech-1.1/wavs/LJ008-0236.wav|coiled up on the floor of the scaffold like a serpent, the hangman's rope!
LJSpeech-1.1/wavs/LJ014-0070.wav|a heavy brutish fellow, was yet aghast at his wife's resolve, and tried hard to dissuade her from bad purpose.
LJSpeech-1.1/wavs/LJ014-0307.wav|were intended by the protectionists to depress the wheat market, and secure the support of the farmers at the forthcoming election;
LJSpeech-1.1/wavs/LJ017-0144.wav|There was no convincing proof that the accused had administered the poison, although beyond question that poison had occasioned the death.
LJSpeech-1.1/wavs/LJ011-0163.wav|She was not in immediate danger, but she wished to see her daughter, "as it was possible she might soon become incapable of recognizing any one."
LJSpeech-1.1/wavs/LJ025-0061.wav|Agardh and other of the botanists of Cuvier's generation who occupied themselves with the lower plants had observed that,
LJSpeech-1.1/wavs/LJ004-0078.wav|"The convicted delinquent has his rights," said Mr. Buxton authoritatively.
LJSpeech-1.1/wavs/LJ031-0005.wav|approximately four miles from the Texas School Book Depository Building.
LJSpeech-1.1/wavs/LJ046-0045.wav|it is the President's right and duty to be the active leader of his party, as when he seeks to be reelected or to maintain his party in power.
LJSpeech-1.1/wavs/LJ014-0323.wav|The warrant thus represented money, and was often used as such, being endorsed and passed from hand to hand as other negotiable bills.
LJSpeech-1.1/wavs/LJ029-0047.wav|maintains records of people who have threatened the President or so conducted themselves as to be deemed a potential danger to him.
LJSpeech-1.1/wavs/LJ042-0123.wav|A "patriotic duty" to bring in the harvest. The opinions of the workers (unvoiced) are that it's a great pain in the neck:
LJSpeech-1.1/wavs/LJ019-0389.wav|passed under the more direct control of the State.
LJSpeech-1.1/wavs/LJ007-0199.wav|baths, fumigating places for clothing, wash-house, and the removal of dust-bins, completed the new arrangements in the main prison.
LJSpeech-1.1/wavs/LJ014-0117.wav|An examination of her boxes disclosed a quantity of O'Connor's property.
LJSpeech-1.1/wavs/LJ004-0013.wav|some prisons that had been ameliorated under the persuasive influence of his kind advice were relapsing into their former horrid state of privation,
LJSpeech-1.1/wavs/LJ017-0086.wav|For this purpose he gave, or there was the strongest presumption that he gave,
LJSpeech-1.1/wavs/LJ008-0002.wav|I propose to return now to the subject of Newgate executions,
LJSpeech-1.1/wavs/LJ028-0471.wav|Nebuchadnezzar says that he built it of burned bricks, but only sun-dried bricks laid in mud now appear.
LJSpeech-1.1/wavs/LJ044-0185.wav|He engaged in an angry argument with the consul who finally told him that, quote, as far as he was concerned
LJSpeech-1.1/wavs/LJ026-0094.wav|This, however, is probably not a source of vital energy, but only contributes to the maintenance of the body temperature.
LJSpeech-1.1/wavs/LJ004-0196.wav|There was an infirmary, properly found and duly looked after.
LJSpeech-1.1/wavs/LJ032-0158.wav|On November twenty-three, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ037-0219.wav|Oswald's Jacket
LJSpeech-1.1/wavs/LJ008-0167.wav|No one who fell ever rose again.
LJSpeech-1.1/wavs/LJ008-0073.wav|One case is preserved by Catnach,
LJSpeech-1.1/wavs/LJ047-0134.wav|The FBI was advised by the rental agent for the Oswalds' apartment in New Orleans that they had moved again.
LJSpeech-1.1/wavs/LJ031-0213.wav|Under "Pathological Diagnosis" the cause of death was set forth as "Gunshot wound, head."
LJSpeech-1.1/wavs/LJ035-0124.wav|Neither Jarman, Norman, Williams, or Dougherty saw Oswald.
LJSpeech-1.1/wavs/LJ014-0190.wav|Marley, disturbed, picked up a cigar and parcel from the counter, then ran out, pursued by Lerigo only.
LJSpeech-1.1/wavs/LJ040-0145.wav|Dr. Hartogs did find Oswald to be a tense, withdrawn, and evasive boy who intensely disliked talking about himself and his feelings.
LJSpeech-1.1/wavs/LJ017-0124.wav|He frequently declared before and during the trial that it would be impossible to find him guilty.
LJSpeech-1.1/wavs/LJ001-0127.wav|the modern letters are narrowed by a third or thereabout; but while this gain of space very much hampers the possibility of beauty of design,
LJSpeech-1.1/wavs/LJ009-0122.wav|particularly to those who desire now to offer up their praises and thanksgivings for thy late mercies vouchsafed unto them.
LJSpeech-1.1/wavs/LJ006-0204.wav|In the same way the wardsman laid in his stock to be retailed. Other light literature besides the daily journals were in circulation:
LJSpeech-1.1/wavs/LJ042-0241.wav|Soon after his arrival he wrote to the Soviet Embassy in Washington
LJSpeech-1.1/wavs/LJ009-0229.wav|Later on, after dark, some friends of the deceased stole the body and buried it in the sand, and this was the end of hanging in chains.
LJSpeech-1.1/wavs/LJ014-0062.wav|He had failed in this as well as in the business of a publican, which he had at one time adopted.
LJSpeech-1.1/wavs/LJ026-0047.wav|circulation, metabolism, excretion, oxygenation (part of respiration),
LJSpeech-1.1/wavs/LJ038-0051.wav|Two patrons of the theatre and John Brewer
LJSpeech-1.1/wavs/LJ036-0014.wav|Oswald's Movements After Leaving Depository Building
LJSpeech-1.1/wavs/LJ023-0050.wav|overlook the simple fact that the President, as Chief Executive, is himself one of the three horses.
LJSpeech-1.1/wavs/LJ019-0125.wav|But an open farm of a thousand acres would have offered abundant chances of escape, which some at least would have attempted, probably with success.
LJSpeech-1.1/wavs/LJ004-0155.wav|In the crowd, all of them persons who had "no other avocation or mode of livelihood but thieving," Mr. Buxton counted eleven children
LJSpeech-1.1/wavs/LJ048-0173.wav|arrangements were made for building and roof security by posting police officers where appropriate.
LJSpeech-1.1/wavs/LJ038-0028.wav|Brewer met McDonald and the other policemen at the alley exit door,
LJSpeech-1.1/wavs/LJ048-0088.wav|Examination of these procedures shows that in most respects they were well conceived and ably executed by the personnel of the Service.
LJSpeech-1.1/wavs/LJ028-0448.wav|All of the ancient writers agree in saying that Babylon was surrounded with both inner and outer walls, and the ruins confirm their statements.
LJSpeech-1.1/wavs/LJ015-0165.wav|But the peer rushed forward and shook Redpath warmly by the hand.
LJSpeech-1.1/wavs/LJ033-0136.wav|A handmade bag of wrapping paper and tape was found in the southeast corner of the sixth floor alongside the window from which the shots were fired.
LJSpeech-1.1/wavs/LJ015-0226.wav|After hanging about the Folkestone office for some time, they saw at last that the key was kept in a certain cupboard.
LJSpeech-1.1/wavs/LJ015-0054.wav|Police officers went down at night to Nutfield, near Reigate, and arrested Sir John Paul, but allowed the prisoner to sleep there.
LJSpeech-1.1/wavs/LJ048-0017.wav|We satisfied ourselves that we had met our requirement, namely to find out whether he had been recruited by Soviet intelligence. The case was closed.
LJSpeech-1.1/wavs/LJ050-0211.wav|Chief Rowley testified that the present workload of each Secret Service agent averages one hundred ten point one cases.
LJSpeech-1.1/wavs/LJ012-0141.wav|Moss presently turned approver,
LJSpeech-1.1/wavs/LJ028-0298.wav|Surely thou hadst gone out of thy mind when thou didst so misuse thyself.
LJSpeech-1.1/wavs/LJ035-0112.wav|The west elevator was not on the fifth floor when Baker and Truly reached that floor,
LJSpeech-1.1/wavs/LJ036-0137.wav|And he never said anything. So I figured he was one of these people that don't like to talk so I never said any more to him.
LJSpeech-1.1/wavs/LJ038-0144.wav|that must have been some other time he picked me up, end quote,
LJSpeech-1.1/wavs/LJ017-0138.wav|Three years later came the case of Dr. Smethurst,
LJSpeech-1.1/wavs/LJ049-0221.wav|perhaps upon recommendations based on further studies by the Cabinet-level committee recommended above or the National Security Council.
LJSpeech-1.1/wavs/LJ031-0160.wav|The police were cautioned to prevent picture taking.
LJSpeech-1.1/wavs/LJ018-0138.wav|Some time in eighteen sixty-two, a large deficiency in stock of bank paper unglazed was discovered at the mills.
LJSpeech-1.1/wavs/LJ016-0324.wav|But it is curious to note that there were several dissentients among the commissioners to this paragraph of the report.
LJSpeech-1.1/wavs/LJ007-0216.wav|For nearly twenty-two hours out of the twenty-four the prisoners are locked up, during which time no officer is stationed in the ward with them.
LJSpeech-1.1/wavs/LJ044-0214.wav|reported Castro as saying Cuba could not accept a situation where at the same time the United States was trying to ease world tensions
LJSpeech-1.1/wavs/LJ045-0111.wav|They asked for Lee Oswald who was not called to the telephone because he was known by the other name.
LJSpeech-1.1/wavs/LJ031-0211.wav|weighed one hundred seventy pounds, had blue eyes and reddish-brown hair.
LJSpeech-1.1/wavs/LJ005-0046.wav|The good it tried to do took active shape in the establishment of temporary refuges -- at Hoxton for males, and in the Hackney Road for females
LJSpeech-1.1/wavs/LJ050-0245.wav|In view of the ever-increasing mobility of American Presidents, it seems unlikely that the Service could or should increase its own staff to a size
LJSpeech-1.1/wavs/LJ040-0028.wav|When he was in the United States he resented the capitalist system which he thought was exploiting him and others like him.
LJSpeech-1.1/wavs/LJ003-0084.wav|Quote, a common-sized man, says the keeper, Mr. Newman, can turn in nineteen inches, end quote.
LJSpeech-1.1/wavs/LJ007-0175.wav|but in opposition to the recorded denunciations of authority, and in defiance of the express enactments of the law,
LJSpeech-1.1/wavs/LJ050-0278.wav|the recommendations we have here suggested would greatly advance the security of the office without any impairment of our fundamental liberties.
LJSpeech-1.1/wavs/LJ014-0275.wav|but it was long before the public realized that the fraudulent clerk and the great theatrical manager were one and the same person.
LJSpeech-1.1/wavs/LJ005-0119.wav|No attempt was made to maintain discipline.
LJSpeech-1.1/wavs/LJ040-0124.wav|This continued despite the efforts of the school authorities and, to a lesser extent, of his mother to have him return to school.
LJSpeech-1.1/wavs/LJ006-0065.wav|were associated together, "of every variety of age, habit, and delinquency, without employment, oversight, or control."
LJSpeech-1.1/wavs/LJ005-0077.wav|"expedient to introduce such measures and arrangements as shall not only provide for the safe custody,
LJSpeech-1.1/wavs/LJ015-0039.wav|Money they must have, and money they raised to meet their urgent necessities upon the balances and securities deposited with them by their customers.
LJSpeech-1.1/wavs/LJ003-0258.wav|Hence the frequent cases of drunkenness, of which no notice was taken, unless people grew riotous in their cups
LJSpeech-1.1/wavs/LJ031-0222.wav|The surgeons observed, through X-ray analysis, thirty or forty tiny dustlike fragments of metal
LJSpeech-1.1/wavs/LJ048-0119.wav|The only systematic supervision of the activities of the advance agent
LJSpeech-1.1/wavs/LJ026-0102.wav|but root pressure due to osmosis, capillary action and evaporation from the leaves are factors.
LJSpeech-1.1/wavs/LJ007-0116.wav|A few others, who could not afford a payment of more than half a guinea, were permitted to monopolize a part of the prison infirmary,
LJSpeech-1.1/wavs/LJ023-0038.wav|The courts, however, have cast doubts on the ability of the elected Congress to protect us against catastrophe
LJSpeech-1.1/wavs/LJ005-0172.wav|When that time arrives
LJSpeech-1.1/wavs/LJ036-0114.wav|Only two of the men in the lineup with Oswald were teenagers: John T. Horn, aged eighteen, was Number one;
LJSpeech-1.1/wavs/LJ009-0079.wav|The sermon of this day, whether eloquent or plain, useful or useless, must produce a striking effect at the moment of its delivery.
LJSpeech-1.1/wavs/LJ016-0445.wav|Miller, the Chelsea murderer, who packed his victim's body in a box, and tried to send it by parcels delivery, tried to kill himself,
LJSpeech-1.1/wavs/LJ003-0003.wav|Prisoners were committed to it quite without reference to its capacity.
LJSpeech-1.1/wavs/LJ048-0278.wav|The Commission recognizes that the responsibilities of members of the White House detail of the Secret Service are arduous.
LJSpeech-1.1/wavs/LJ025-0032.wav|Hence arose the second great distinctive character of animals, or the circulatory system, which is less important than the digestive,
LJSpeech-1.1/wavs/LJ014-0280.wav|But it was proved that Watts had appropriated one cheque for fourteen hundred pounds,
LJSpeech-1.1/wavs/LJ025-0041.wav|and carbonic acid containing carbon and oxygen.
LJSpeech-1.1/wavs/LJ026-0003.wav|Nutrition thus, as has been pointed out, makes it possible to classify most organisms as animals or plants.
LJSpeech-1.1/wavs/LJ039-0004.wav|Chapter four. The Assassin: Part eight.
LJSpeech-1.1/wavs/LJ022-0060.wav|We must begin now to make provision for the future.
LJSpeech-1.1/wavs/LJ046-0064.wav|The President's views of his responsibilities as President of the United States were that he meet the people, that he go out to their homes and see them,
LJSpeech-1.1/wavs/LJ005-0114.wav|In others the separation between the sexes consisted in a hanging curtain
LJSpeech-1.1/wavs/LJ029-0130.wav|the President's motorcade would pass the Texas School Book Depository Building on the northwest corner of Houston and Elm Streets.
LJSpeech-1.1/wavs/LJ033-0106.wav|believed that he saw Oswald coming to work, but he does not remember that Oswald had anything in his hands as he entered the door.
LJSpeech-1.1/wavs/LJ019-0160.wav|and check by remonstrance or threat of punishment all who broke the peace of the prison.
LJSpeech-1.1/wavs/LJ046-0053.wav|In recent years, Presidential journeys have been frequent and extensive,
LJSpeech-1.1/wavs/LJ028-0238.wav|he then himself drew off with the unwarlike portion of his host, and made for the place where Nitocris dug the basin for the river,
LJSpeech-1.1/wavs/LJ038-0023.wav|At one:forty-five p.m., the police radio stated, quote, Have information a suspect just went in the Texas Theatre on West Jefferson, end quote.
LJSpeech-1.1/wavs/LJ003-0344.wav|all chances of classification and separation vanished, and the greatest evils remained untouched.
LJSpeech-1.1/wavs/LJ046-0156.wav|The general files of PRS consist of folders on individuals, card indexed by name.
LJSpeech-1.1/wavs/LJ031-0154.wav|Secret Service agents stationed at later stops on the President's itinerary of November twenty-two were redeployed.
LJSpeech-1.1/wavs/LJ033-0211.wav|and the obvious bulk of the package which he intended to bring to work the next day;
LJSpeech-1.1/wavs/LJ004-0209.wav|The looms were constantly busy. Tailors were always at work, and every article of clothing and bedding was made up within the walls.
LJSpeech-1.1/wavs/LJ042-0079.wav|My request for citizenship is now pending before the Supreme Soviet of the U.S.S.R. I take these steps for political reasons.
LJSpeech-1.1/wavs/LJ031-0142.wav|The Vice President conferred with White House Assistant Press Secretary Malcolm Kilduff
LJSpeech-1.1/wavs/LJ028-0107.wav|The ancients never tired of describing them.
LJSpeech-1.1/wavs/LJ018-0010.wav|Inside the carriage was a hat, a walking-stick, and a small black leather bag.
LJSpeech-1.1/wavs/LJ028-0510.wav|Probably their metal was far too valuable for the enemy to leave behind.
LJSpeech-1.1/wavs/LJ043-0008.wav|De Mohrenschildt was a peripheral member of the so-called Russian community, with which Oswald made contact through Mr. Peter Gregory,
LJSpeech-1.1/wavs/LJ034-0131.wav|a person squatting or kneeling exposes more of his body than would normally be the case.
LJSpeech-1.1/wavs/LJ019-0382.wav|As the years passed, great want of uniformity continued to prevail throughout the prisons of the United Kingdom.
LJSpeech-1.1/wavs/LJ019-0320.wav|was the boon to which willing industry extending over a long period established a certain claim.
LJSpeech-1.1/wavs/LJ039-0186.wav|would have been to fire three times and hit the target twice within a span of four point eight to five point six seconds.
LJSpeech-1.1/wavs/LJ049-0193.wav|Consequently the suggestion has been made, on the one hand, that all preventive investigative functions relating to the security of the President
LJSpeech-1.1/wavs/LJ021-0123.wav|When the businessmen of the country were demanding the right to organize themselves adequately to promote their legitimate interests;
LJSpeech-1.1/wavs/LJ001-0150.wav|the page so lay on the paper that there was more space allowed to the bottom and fore margin than to the top and back of the paper,
LJSpeech-1.1/wavs/LJ028-0299.wav|"Had I told thee," rejoined the other, "what I was bent on doing, thou wouldst not have suffered it;
LJSpeech-1.1/wavs/LJ022-0134.wav|Neither you nor I want criticism conceived in a purely fault-finding or partisan spirit,
LJSpeech-1.1/wavs/LJ022-0041.wav|Its first objective is to put men and women now on the relief rolls to work and, incidentally,
LJSpeech-1.1/wavs/LJ008-0229.wav|Above the murmur and tumult of that noisy assembly, the lowing and bleating of cattle as they were driven into the stalls and pens of Smithfield
LJSpeech-1.1/wavs/LJ033-0003.wav|The rifle in the building.
LJSpeech-1.1/wavs/LJ022-0021.wav|or to one industry, or to an individual private occupation.
LJSpeech-1.1/wavs/LJ050-0128.wav|Much useful information will come to the attention of local law enforcement agencies in the regular course of their activities,
LJSpeech-1.1/wavs/LJ047-0095.wav|On the next day, he asked the New Orleans police to arrange for him to be interviewed by the FBI.
LJSpeech-1.1/wavs/LJ043-0037.wav|At the time of his defection, Oswald had said that neither his brother, Robert,
LJSpeech-1.1/wavs/LJ012-0150.wav|Mrs. Abrahams imposed upon her father by abstracting a portion of the dust and selling it on her own account;
LJSpeech-1.1/wavs/LJ042-0028.wav|Oswald had managed to save enough money to cover the expenses of his forthcoming trip.
LJSpeech-1.1/wavs/LJ041-0080.wav|in those arguments, quote, and make himself come out top dog, end quote.
LJSpeech-1.1/wavs/LJ002-0068.wav|Here were also lodged the gatesmen, the prisoners who had charge of the inner gates, and who were entrusted with the duty of escorting visitors from the gates
LJSpeech-1.1/wavs/LJ016-0255.wav|The old prejudices, such as that which enlisted Dr. Johnson on the side of the Tyburn procession, still lingered and prevented any change.
LJSpeech-1.1/wavs/LJ019-0292.wav|Prisoners still slept two in a bed.
LJSpeech-1.1/wavs/LJ009-0156.wav|"with a view," as he himself said, "to his professional studies."
LJSpeech-1.1/wavs/LJ022-0199.wav|Fear is vanishing and confidence is growing on every side,
LJSpeech-1.1/wavs/LJ043-0071.wav|His performance for that company was satisfactory.
LJSpeech-1.1/wavs/LJ011-0038.wav|Fauntleroy meanwhile lay in Newgate, not herded with other condemned prisoners, as the custom was,
LJSpeech-1.1/wavs/LJ006-0108.wav|He charged a weekly sum as ward dues for the use of knives, forks, and plates
LJSpeech-1.1/wavs/LJ026-0125.wav|But the formation of starch, all important as it is, is after all only the manufacture of food
LJSpeech-1.1/wavs/LJ029-0041.wav|who was the Secret Service official responsible for the entire Texas journey.
LJSpeech-1.1/wavs/LJ039-0089.wav|in relation to the target as opposed to iron sights with aligning the sights and then aligning them on the target, end quote.
LJSpeech-1.1/wavs/LJ035-0120.wav|While they were at the west windows their view of the stairwell was completely blocked by shelves and boxes.
LJSpeech-1.1/wavs/LJ019-0360.wav|This he might do on the representation of the inspector of prisons,
LJSpeech-1.1/wavs/LJ032-0183.wav|The relative freshness of the fibers is strong evidence that they were caught on the rifle on the morning of the assassination or during the preceding evening.
LJSpeech-1.1/wavs/LJ031-0046.wav|and an extensive wound in the President's head where a sizable portion of the skull was missing.
LJSpeech-1.1/wavs/LJ030-0180.wav|Roy Kellerman, in the right front seat of the limousine, heard a report like a firecracker pop.
LJSpeech-1.1/wavs/LJ028-0051.wav|He enlarged the old city, erected temples, and began the construction of its walls.
LJSpeech-1.1/wavs/LJ015-0127.wav|All the signatures in the transfer were forged. Not only did he thus transfer and realize "bogus" stock
LJSpeech-1.1/wavs/LJ025-0082.wav|But although Cuvier's leading diagnosis of the animal from the plant will not stand a strict test,
LJSpeech-1.1/wavs/LJ013-0209.wav|he was annoyed with his man for various small omissions and acts of forgetfulness, and on the night of the murder had taken Courvoisier to task rather sharply.
LJSpeech-1.1/wavs/LJ011-0011.wav|and took the instrument out to a clerk with the ink not dry.
LJSpeech-1.1/wavs/LJ034-0151.wav|of what he said on November twenty-two.
LJSpeech-1.1/wavs/LJ039-0064.wav|An aerial photograph of Dealey Plaza shows that Elm Street runs at an angle
LJSpeech-1.1/wavs/LJ011-0211.wav|when indictments were preferred against both brothers "for having carried away Ellen Turner, spinster,
LJSpeech-1.1/wavs/LJ026-0064.wav|but unlike that of the animal, it is not chiefly an income of foods, but only of the raw materials of food.
LJSpeech-1.1/wavs/LJ019-0143.wav|Drinking and gaming,
LJSpeech-1.1/wavs/LJ010-0268.wav|It happened that a lad named Bean had absconded from his father's home some weeks before,
LJSpeech-1.1/wavs/LJ049-0119.wav|would be conducted by Federal law enforcement officials, in particular, the FBI with the assistance of the Secret Service.
LJSpeech-1.1/wavs/LJ005-0215.wav|The regular daily visitation of the chaplain was also insisted upon.
LJSpeech-1.1/wavs/LJ042-0204.wav|but in servile conformity to the wishes of the Soviet Union and in anticipation of Soviet Russia's complete domination of the American continent.
LJSpeech-1.1/wavs/LJ018-0168.wav|but proofs of Griffiths' guilt were at once apparent on entering his work-room.
LJSpeech-1.1/wavs/LJ002-0200.wav|The marshal was supposed to be resident either within the prison or the rules.
LJSpeech-1.1/wavs/LJ018-0019.wav|The stick and bag were his, but not the hat.
LJSpeech-1.1/wavs/LJ036-0143.wav|He marked what, he thought was the intersection of Neches and Beckley on a map of Dallas with a large "X."
LJSpeech-1.1/wavs/LJ028-0490.wav|He would have had to cross a deep moat, to scale a wall of burned bricks about twenty feet in thickness and perhaps three times as high,
LJSpeech-1.1/wavs/LJ033-0007.wav|the circumstances surrounding Oswald's return to Irving, Texas, on Thursday, November twenty-one, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ008-0101.wav|exuberant in talk and hissing hot from Pie Corner, where she had taken her morning dose of gin-and-bitters.
LJSpeech-1.1/wavs/LJ014-0054.wav|a maidservant, Sarah Thomas, murdered her mistress, an aged woman, by beating out her brains with a stone.
LJSpeech-1.1/wavs/LJ047-0088.wav|We did not request the State Department to include Oswald on a list which would have resulted in advising us of any application for a passport
LJSpeech-1.1/wavs/LJ045-0158.wav|He spent quite a bit of time putting away diapers and played with the children on the street.
LJSpeech-1.1/wavs/LJ044-0074.wav|an agent of Bringuier's attempting to learn more about the true nature
LJSpeech-1.1/wavs/LJ027-0180.wav|The general similarity of the three series is complete.
LJSpeech-1.1/wavs/LJ046-0148.wav|that the safety of the President is or might be in danger, either at the present or in the future.
LJSpeech-1.1/wavs/LJ027-0012.wav|All have the same ultimate substance
LJSpeech-1.1/wavs/LJ042-0132.wav|Return to the United States. In view of the intensity of his earlier commitment to the Soviet Union,
LJSpeech-1.1/wavs/LJ016-0123.wav|got hold of the step ladder used in lighting the gas, and which under our more careful supervision would have been, as now-a-days, chained up.
LJSpeech-1.1/wavs/LJ045-0161.wav|He was upset over the fact that I would not answer him.
LJSpeech-1.1/wavs/LJ001-0179.wav|even when the woodcuts are very rude indeed,
LJSpeech-1.1/wavs/LJ021-0154.wav|is the program of Public Works provided for in the same Act and designed to put more men back to work,
LJSpeech-1.1/wavs/LJ016-0136.wav|On the other hand, at the great convict establishments, such is the moral restraint of a systematic discipline,
LJSpeech-1.1/wavs/LJ044-0006.wav|Although, as indicated above, the Commission has been unable to find any credible evidence
LJSpeech-1.1/wavs/LJ012-0092.wav|This occurred in November eighteen thirty-four. The Custom House officials were in a state of consternation,
LJSpeech-1.1/wavs/LJ024-0125.wav|This proposal of mine will not infringe in the slightest upon the civil or religious liberties so dear to every American.
LJSpeech-1.1/wavs/LJ037-0156.wav|also examined the four cartridge cases found near the site of the homicide and compared them with the test cartridge cases fired from the Smith and Wesson revolver
LJSpeech-1.1/wavs/LJ042-0046.wav|This should answer your question, and also give you a glimpse of my way of thinking. So you speak of advantages. Do you think that is why I am here?
LJSpeech-1.1/wavs/LJ040-0230.wav|There are indications that he has suffered serious personality damage but if he can receive help quickly this might be repaired to some extent, end quote.
LJSpeech-1.1/wavs/LJ040-0232.wav|Few social agencies even in New York were equipped to provide the kind of intensive treatment that he needed,
LJSpeech-1.1/wavs/LJ025-0089.wav|The third distinction is based on a completely erroneous conception of the chemical differences
LJSpeech-1.1/wavs/LJ023-0060.wav|and the powers given to the Congress to carry out those purposes can be best described by saying
LJSpeech-1.1/wavs/LJ046-0062.wav|His friend and Special Assistant Kenneth O'Donnell, who accompanied him on his last visit to Dallas,
LJSpeech-1.1/wavs/LJ016-0097.wav|which with Wakefield was utilized as a receptacle for convicts not going to Western Australia,
LJSpeech-1.1/wavs/LJ001-0054.wav|Jenson, however, had many contemporaries who used beautiful type,
LJSpeech-1.1/wavs/LJ046-0249.wav|about persons other than those who were obvious threats to the President.
LJSpeech-1.1/wavs/LJ042-0037.wav|and under which, quote, art, culture and the sprit of man are subjected to commercial enterprising,
LJSpeech-1.1/wavs/LJ005-0090.wav|the first by daily services, the latter by the appointment of schoolmasters and instruction in reading and writing.
LJSpeech-1.1/wavs/LJ029-0166.wav|On November twenty a front page story reported that the streets on which the Presidential motorcade would travel included "Main and Stemmons Freeway."
LJSpeech-1.1/wavs/LJ043-0035.wav|Shortly after his return from the Soviet Union, Oswald severed all relations with his mother;
LJSpeech-1.1/wavs/LJ041-0142.wav|Once it had started down Elm Street toward the Triple Underpass, however,
LJSpeech-1.1/wavs/LJ007-0036.wav|one man declared that the language of the condemned rooms was disgusting, that he was dying a death every day in being compelled to associate with such characters.
LJSpeech-1.1/wavs/LJ015-0278.wav|commencing sham actions, and addressing formal applications, merely for the reply.
LJSpeech-1.1/wavs/LJ016-0271.wav|The reply evinced equal satisfaction, and the speaker, with a profane oath, declared that he would like to act as Jack Ketch to the whole lot.
LJSpeech-1.1/wavs/LJ007-0093.wav|The matter was still further complicated at Newgate by the presence within the walls of sham lunatics. Some of those included in the category
LJSpeech-1.1/wavs/LJ009-0056.wav|The last of the four is said to have been a clergyman of the Church of England, condemned for forgery, "a miserable old man in a tattered suit of black.
LJSpeech-1.1/wavs/LJ050-0098.wav|determination to use a means, other than legal or peaceful, to satisfy his grievance, end quote, within the meaning of the new criteria.
LJSpeech-1.1/wavs/LJ018-0030.wav|Last of all, the cabman swore that he had bought the very hat found in the carriage for Müller at the hatter's, Walker's of Crawford Street.
LJSpeech-1.1/wavs/LJ006-0104.wav|but its issue was precarious, and dependent on the good will of the wardsmen, who measured out the portions to each according to his eye,
LJSpeech-1.1/wavs/LJ005-0229.wav|By another clause of the Jail Act, two justices were to be appointed to visit the prison at least thrice in every quarter, and "oftener if occasion required."
LJSpeech-1.1/wavs/LJ034-0196.wav|Another person who saw the assassin as the shots were fired was Amos L. Euins, age fifteen,
LJSpeech-1.1/wavs/LJ012-0105.wav|The police were of opinion that these robberies were both the work of the same hand.
LJSpeech-1.1/wavs/LJ039-0008.wav|told Robert Oswald, Lee Harvey Oswald's brother, that Oswald had once threatened to shoot former Vice President Richard M. Nixon.
LJSpeech-1.1/wavs/LJ011-0189.wav|the other brother was accordingly sent on a pretended mission to Shrigley to bring Mr. Turner on to London, whither Wakefield and Miss Turner also proceeded.
LJSpeech-1.1/wavs/LJ029-0007.wav|this chapter reviews the motorcade through Dallas, the fleeting moments of the assassination,
LJSpeech-1.1/wavs/LJ014-0329.wav|and so developed his business that in one year his transactions amounted to a couple of millions of pounds.
LJSpeech-1.1/wavs/LJ014-0225.wav|A handsome sum was subscribed for the injured constable, who was disabled for life.
LJSpeech-1.1/wavs/LJ016-0088.wav|working at the roof of the chapel on the female side.
LJSpeech-1.1/wavs/LJ008-0127.wav|As we were crossing the press yard,
LJSpeech-1.1/wavs/LJ001-0125.wav|this is the narrowing of the modern letters.
LJSpeech-1.1/wavs/LJ006-0022.wav|At that time the mild and intelligent prison discipline in force in Pennsylvania, the legacy of the old Quaker immigrants,
LJSpeech-1.1/wavs/LJ038-0245.wav|A photography expert with the FBI
LJSpeech-1.1/wavs/LJ044-0017.wav|He distributed literature in downtown New Orleans on August nine, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ032-0273.wav|(four) a photograph taken in the yard of Oswald's apartment showed him holding this rifle, and (five)
LJSpeech-1.1/wavs/LJ001-0143.wav|For where these are boldly and carefully designed, and each letter is thoroughly individual in form,
LJSpeech-1.1/wavs/LJ003-0005.wav|no steps taken to reduce the number of committals, and the governor was obliged to utilize the chapel as a day and night room.
LJSpeech-1.1/wavs/LJ046-0169.wav|If the field office determines that the case should be subject to continuing review, PRS establishes a file
LJSpeech-1.1/wavs/LJ033-0017.wav|who also worked at the Depository.
LJSpeech-1.1/wavs/LJ038-0287.wav|Additional corroborative evidence.
LJSpeech-1.1/wavs/LJ048-0079.wav|mutual understanding of FBI and agency jurisdictions, and an indicated willingness by the agency representative
LJSpeech-1.1/wavs/LJ002-0017.wav|Trustworthy evidence is forthcoming to the effect that these high figures were constantly maintained for many months at a time.
LJSpeech-1.1/wavs/LJ047-0231.wav|some indication that the person planned to take some action against the safety of the President of the United States or the Vice President. End quote.
LJSpeech-1.1/wavs/LJ007-0018.wav|and that when the restraining influences of the ladies were absent, the female prisoners relapsed into immoral and uncleanly discourse.
LJSpeech-1.1/wavs/LJ017-0047.wav|the rest of the available space was allotted by ticket, to secure which the greatest influence was necessary.
LJSpeech-1.1/wavs/LJ014-0339.wav|asked Davidson and Gordon, a firm with which Cole was closely allied, whether the warrants meant goods or nothing.
LJSpeech-1.1/wavs/LJ022-0046.wav|It is true that while business and industry are definitely better our relief rolls are still too large.
LJSpeech-1.1/wavs/LJ010-0189.wav|He asked more than once whether the Queen was hurt, and acknowledged that the pistols were loaded with ball.
LJSpeech-1.1/wavs/LJ028-0019.wav|The stars come out one by one and shine brighter than elsewhere as if to light you on your way.
LJSpeech-1.1/wavs/LJ026-0021.wav|nitrogen is obtained from simple salts and the nutritive processes result in deoxidation;
LJSpeech-1.1/wavs/LJ002-0283.wav|and denied admission to the "charity wards," which partook of all the benefits of bequests and donations to poor debtors.
LJSpeech-1.1/wavs/LJ036-0047.wav|On November twenty-two, Mrs. Bledsoe came downtown to watch the Presidential motorcade.
LJSpeech-1.1/wavs/LJ028-0112.wav|My father did that which no previous king had done.
LJSpeech-1.1/wavs/LJ009-0176.wav|Seven other crimes, however, were still capital by law, and so continued till the passing of the Criminal Consolidation Acts of eighteen sixty-one.
LJSpeech-1.1/wavs/LJ028-0423.wav|In eighteen twelve, James Claudius Rich, the British Resident at Baghdad, made the first complete examination of the ruins.
LJSpeech-1.1/wavs/LJ003-0202.wav|These capital convicts, says Mr. Bennet, quote, lessened the ennui and despair of their situation by unbecoming merriment
LJSpeech-1.1/wavs/LJ020-0108.wav|Other things besides rising dough get on quite as well without your standing by to watch them.
LJSpeech-1.1/wavs/LJ014-0223.wav|The judge, in passing sentence of death, told him he richly deserved the punishment.
LJSpeech-1.1/wavs/LJ028-0351.wav|As for Zopyrus he was considered by Darius to have surpassed, in the greatness of his achievements, all other Persians,
LJSpeech-1.1/wavs/LJ028-0496.wav|rising higher and higher, like a great terraced, turreted mountain.
LJSpeech-1.1/wavs/LJ032-0190.wav|On the other hand Stombaugh pointed out that fibers might retain their freshness if the rifle had been
LJSpeech-1.1/wavs/LJ009-0181.wav|that authentic cases were known previous to the first cited act of criminals selling their own bodies to surgeons for dissection.
LJSpeech-1.1/wavs/LJ050-0148.wav|the increased information supplied by other agencies will be wasted.
LJSpeech-1.1/wavs/LJ010-0247.wav|The prisoner was conveyed without delay to the Home Office, and there examined by the Privy Council, which had been hastily summoned for the purpose.
LJSpeech-1.1/wavs/LJ039-0224.wav|show that he possessed ample capability to commit the assassination.
LJSpeech-1.1/wavs/LJ047-0108.wav|During the interview Quigley obtained background information from Oswald which was inconsistent with information already in the Bureau's possession.
LJSpeech-1.1/wavs/LJ017-0158.wav|She had a little fortune of her own, some one thousand seven hundred pounds or one thousand eight hundred pounds,
LJSpeech-1.1/wavs/LJ049-0183.wav|regarding such threats and that its Protective Research Section is not adequately staffed or equipped
LJSpeech-1.1/wavs/LJ031-0057.wav|While Dr. Perry was performing the tracheotomy, Drs. Carrico and Ronald Jones made cutdowns on the President's right leg and left arm, respectively,
LJSpeech-1.1/wavs/LJ004-0158.wav|All were in ill health; almost all were in rags; almost all were filthy in the extreme.
LJSpeech-1.1/wavs/LJ043-0050.wav|As Marguerite Oswald testified, quote,
LJSpeech-1.1/wavs/LJ023-0119.wav|that will refuse to amend the Constitution by the arbitrary exercise of judicial power -- amended by judicial say-so.
LJSpeech-1.1/wavs/LJ021-0015.wav|The underlying necessity for such activity
LJSpeech-1.1/wavs/LJ027-0125.wav|in the Python we find very tiny rudiments of the hindlimbs. Now,
LJSpeech-1.1/wavs/LJ016-0153.wav|would make death a certainty, so limited and imperfect are the means generally available.
LJSpeech-1.1/wavs/LJ040-0172.wav|Mrs. Siegel concluded that Lee, quote, just felt that his mother never gave a damn for him.
LJSpeech-1.1/wavs/LJ040-0159.wav|who suffers under the impact of really existing emotional isolation
LJSpeech-1.1/wavs/LJ028-0087.wav|Such was the appearance of the builder of the walls of Babylon.
LJSpeech-1.1/wavs/LJ048-0233.wav|Two of the nine agents returned to their rooms. The seven others proceeded to an establishment called the Cellar Coffee House,
LJSpeech-1.1/wavs/LJ038-0288.wav|The admissions made to Marina Oswald by her husband are an important element in the evidence that Lee Harvey Oswald fired the shot at General Walker.
LJSpeech-1.1/wavs/LJ008-0199.wav|At the George public-house to the south of the drop, Sir W. Watkin Wynn, Baronet,
LJSpeech-1.1/wavs/LJ029-0188.wav|Stevenson was jeered, jostled, and spat upon by hostile demonstrators outside the Dallas Memorial Auditorium Theater.
LJSpeech-1.1/wavs/LJ012-0132.wav|and he with his father arranged that a messenger should call for the stuff with forged credentials, and anticipating the rightful owner.
LJSpeech-1.1/wavs/LJ033-0139.wav|Oswald's Mannlicher-Carcano rifle, serial Number C two seven six six, which was also found on the sixth floor.
LJSpeech-1.1/wavs/LJ048-0085.wav|the Commission believes that the liaison between all Federal agencies responsible for Presidential protection should be improved.
LJSpeech-1.1/wavs/LJ006-0209.wav|the donation of a philanthropic gentleman, Captain Brown, but these, particularly the Bibles, bore little appearance of having been used.
LJSpeech-1.1/wavs/LJ028-0283.wav|As soon therefore as he felt within himself that Babylon was fated to be taken, he went to Darius and asked him if he set a very high value on its conquest.
LJSpeech-1.1/wavs/LJ016-0071.wav|Dissatisfied with this remuneration, he again took to the road, and tramped into Hampshire,
LJSpeech-1.1/wavs/LJ043-0064.wav|which were largely of his own making.
LJSpeech-1.1/wavs/LJ043-0039.wav|He also indicated to officials at the American Embassy in Moscow that his defection was motivated at least in part
LJSpeech-1.1/wavs/LJ041-0182.wav|and believed that our Government did not have, quote, too much to offer, end quote, but was not in favor of, quote, the Communist way of life, end quote.
LJSpeech-1.1/wavs/LJ005-0060.wav|The Society did not limit its remarks to the description of what had already been done
LJSpeech-1.1/wavs/LJ036-0131.wav|And about that time an old lady, I think she was an old lady, I don't remember nothing but her sticking her head down past him in the door and said,
LJSpeech-1.1/wavs/LJ026-0067.wav|We have here the direct absorption into the body proper of food-stuffs precisely as the animal takes in water and oxygen.
LJSpeech-1.1/wavs/LJ012-0180.wav|The murderer explained that he had first fired a pistol at Weare's head, but the shot glanced off his cheek.
LJSpeech-1.1/wavs/LJ047-0161.wav|Mrs. Paine told Hosty also
LJSpeech-1.1/wavs/LJ008-0131.wav|the other he kept between his hands.
LJSpeech-1.1/wavs/LJ034-0190.wav|Robert Edwards said that, while looking at the south side of the Depository Building shortly before the motorcade,
LJSpeech-1.1/wavs/LJ041-0074.wav|John E. Donovan, one of his former officers, testified that Oswald thought, quote,
LJSpeech-1.1/wavs/LJ022-0051.wav|In spite of the fact that unemployment remains a serious problem
LJSpeech-1.1/wavs/LJ027-0166.wav|retain permanently this form, and are therefore called "perennibranchs," but the frog still passes on.
LJSpeech-1.1/wavs/LJ038-0249.wav|Investigation determined that this photograph was taken approximately seven-tenths of a mile from Walker's house.
LJSpeech-1.1/wavs/LJ034-0214.wav|Investigation has established that Altgens' picture was taken approximately two seconds after the firing of the shot
LJSpeech-1.1/wavs/LJ046-0077.wav|Under our system, measures must be sought to afford security without impeding the President's performance of his many functions.
LJSpeech-1.1/wavs/LJ006-0121.wav|for a petition of from one shilling, half pence to eight shillings, according to its length,
LJSpeech-1.1/wavs/LJ037-0060.wav|That Mrs. Markham described the man who killed Patrolman Tippit as, quote, short, a little on the heavy side, end quote.
LJSpeech-1.1/wavs/LJ023-0064.wav|Having in mind that in succeeding generations many other problems then undreamed of would become national problems
LJSpeech-1.1/wavs/LJ005-0211.wav|the jail consisted of six cells, frequently so damp that the moisture trickled down the walls; there was not space for air or exercise,
LJSpeech-1.1/wavs/LJ036-0121.wav|a twelve:fifteen p.m. pickup at Continental to Greyhound, unloaded at twelve:thirty p.m.,
LJSpeech-1.1/wavs/LJ029-0002.wav|Chapter two. The Assassination: Part one.
LJSpeech-1.1/wavs/LJ038-0010.wav|a recessed area extending about fifteen feet between the sidewalk and the front door of his store.
LJSpeech-1.1/wavs/LJ023-0018.wav|We also became convinced that the only way to avoid a repetition of those dark days was to have a government with power to prevent
LJSpeech-1.1/wavs/LJ018-0119.wav|His offer was not, however, accepted.
LJSpeech-1.1/wavs/LJ002-0304.wav|The sheriff demanded four shillings, six pence for his liberate, the jailer six shillings, ten pence more, and the turnkey two shillings;
LJSpeech-1.1/wavs/LJ019-0342.wav|So was the employment of prisoners in any position of trust or authority;
LJSpeech-1.1/wavs/LJ043-0131.wav|As a result Oswald was not hired.
LJSpeech-1.1/wavs/LJ035-0048.wav|I can't say whether he had gone on through that door [the lunchroom door] or not.
LJSpeech-1.1/wavs/LJ047-0050.wav|Oswald again agreed to advise the FBI if he were approached under suspicious circumstances; however, he deprecated the possibility of this happening,
LJSpeech-1.1/wavs/LJ027-0045.wav|careful study shows detailed internal as well as external similarities of structure. Such cases are "homologies".
LJSpeech-1.1/wavs/LJ005-0139.wav|making an average of nineteen persons occupying each room.
LJSpeech-1.1/wavs/LJ044-0060.wav|In view of the limited amount of public activity on Oswald's part before August nine, nineteen sixty-three,
LJSpeech-1.1/wavs/LJ050-0070.wav|The FBI now transmits information on all defectors, a category which would, of course, have included Oswald.
LJSpeech-1.1/wavs/LJ009-0275.wav|who bad been further upset by a letter threatening to shoot him when he appeared to perform his task.
LJSpeech-1.1/wavs/LJ025-0066.wav|and his skepticism was the more justified since Ehrenberg in his elaborate and comprehensive work on the infusoria,
LJSpeech-1.1/wavs/LJ039-0240.wav|On the basis of the evidence reviewed in this chapter, the Commission has found that Lee Harvey Oswald (one)
LJSpeech-1.1/wavs/LJ029-0144.wav|In conformity with these arrangements, traffic proceeding west on Main is directed to turn right at Houston
LJSpeech-1.1/wavs/LJ015-0117.wav|Sergeant Ballantine, who prosecuted,
LJSpeech-1.1/wavs/LJ019-0322.wav|On the other hand, new and careful regulations were framed to secure the moral and material well-being of the inmates of the jails.
LJSpeech-1.1/wavs/LJ028-0155.wav|Lumps of bitumen are found in great abundance in this river.
LJSpeech-1.1/wavs/LJ011-0073.wav|several persons were sentenced to or suffered death for this crime.
LJSpeech-1.1/wavs/LJ009-0210.wav|On the left side of the head the fatal mall,
LJSpeech-1.1/wavs/LJ023-0134.wav|and reject the legislative powers which the courts have today assumed.
LJSpeech-1.1/wavs/LJ026-0117.wav|are directly oxidized to excretions and, lacking nitrogen, cannot serve for making new animal protoplasm.
LJSpeech-1.1/wavs/LJ014-0296.wav|He had made use of a piece of rope cut out from the sacking of his bedstead, and had tied his feet together with a silk pocket-handkerchief.
LJSpeech-1.1/wavs/LJ017-0126.wav|He relied on the absence of the strychnia.
LJSpeech-1.1/wavs/LJ034-0103.wav|This description most probably led to the radio alert sent to police cars at approximately twelve:forty-five p.m., which described the suspect as white,
LJSpeech-1.1/wavs/LJ007-0140.wav|The primary object of committing a prisoner to jail, as the inspectors pointed out, was to deter not only the criminal himself, but others from crime,
LJSpeech-1.1/wavs/LJ040-0231.wav|Lee Oswald never received that help.
LJSpeech-1.1/wavs/LJ033-0039.wav|and one which provided an excuse for the carrying of a bulky package the following morning.
LJSpeech-1.1/wavs/LJ050-0143.wav|county, and State law enforcement agencies in their districts.
LJSpeech-1.1/wavs/LJ001-0093.wav|This experiment was so far successful that about eighteen fifty Messrs. Miller and Richard of Edinburgh
LJSpeech-1.1/wavs/LJ048-0118.wav|He did not have a checklist of the tasks he was expected to accomplish, either by his own efforts or with the cooperation of local authorities.
LJSpeech-1.1/wavs/LJ005-0176.wav|which possessed the right of trying criminals for various offenses.
LJSpeech-1.1/wavs/LJ003-0158.wav|from whom still higher fees were exacted, with the same discreditable idea of swelling the revenues of the prison.
LJSpeech-1.1/wavs/LJ047-0115.wav|Several days later, the Bureau received additional evidence that Oswald had lied to Agent Quigley.
|
PyTorch/Recommendation/DLRM/preproc | preproc | run_spark_gpu_DGX-2 | #!/bin/bash
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#########################################################################
# File Name: run_spark_gpu_DGX-2.sh
set -e
# the data path including 1TB criteo data, day_0, day_1, ...
export INPUT_PATH=${1:-'/data/dlrm/criteo'}
# the output path, use for generating the dictionary and the final dataset
# the output folder should have more than 300GB
export OUTPUT_PATH=${2:-'/data/dlrm/output'}
export FREQUENCY_LIMIT=${3:-'15'}
export HARDWARE_PLATFORM='DGX-2'
# spark local dir should have about 3TB
# the temporary path used for spark shuffle write
export SPARK_LOCAL_DIRS='/data/dlrm/spark/tmp'
source DGX-2_config.sh
OPTS="--frequency_limit $FREQUENCY_LIMIT"
export SPARK_HOME=/opt/spark
export JAVA_HOME=/usr/lib/jvm/java-8-openjdk-amd64
export PATH=$SPARK_HOME/bin:$SPARK_HOME/sbin:$PATH
# we use spark standalone to run the job
export MASTER=spark://$HOSTNAME:7077
echo "Starting spark standalone"
start-master.sh
start-slave.sh $MASTER
echo "Generating the dictionary..."
spark-submit --master $MASTER \
--driver-memory "${DRIVER_MEMORY}G" \
--executor-cores $NUM_EXECUTOR_CORES \
--executor-memory "${EXECUTOR_MEMORY}G" \
--conf spark.cores.max=$TOTAL_CORES \
--conf spark.task.cpus=1 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--conf spark.sql.shuffle.partitions=600 \
--conf spark.driver.maxResultSize=2G \
--conf spark.locality.wait=0s \
--conf spark.network.timeout=1800s \
--conf spark.task.resource.gpu.amount=0.01 \
--conf spark.executor.resource.gpu.amount=1 \
--conf spark.plugins=com.nvidia.spark.SQLPlugin \
--conf spark.rapids.sql.concurrentGpuTasks=2 \
--conf spark.rapids.sql.reader.batchSizeRows=4000000 \
--conf spark.rapids.memory.pinnedPool.size=16g \
--conf spark.rapids.sql.explain=ALL \
--conf spark.sql.autoBroadcastJoinThreshold=1GB \
--conf spark.rapids.sql.incompatibleOps.enabled=true \
--conf spark.driver.maxResultSize=2G \
--conf spark.executor.extraJavaOptions="-Dcom.nvidia.cudf.prefer-pinned=true\ -Djava.io.tmpdir=$SPARK_LOCAL_DIRS" \
spark_data_utils.py --mode generate_models \
$OPTS \
--input_folder $INPUT_PATH \
--days 0-23 \
--model_folder $OUTPUT_PATH/models \
--write_mode overwrite --low_mem 2>&1 | tee submit_dict_log.txt
echo "Transforming the train data from day_0 to day_22..."
spark-submit --master $MASTER \
--driver-memory "${DRIVER_MEMORY}G" \
--executor-cores $NUM_EXECUTOR_CORES \
--executor-memory "${EXECUTOR_MEMORY}G" \
--conf spark.cores.max=$TOTAL_CORES \
--conf spark.task.cpus=3 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--conf spark.sql.shuffle.partitions=600 \
--conf spark.driver.maxResultSize=2G \
--conf spark.locality.wait=0s \
--conf spark.network.timeout=1800s \
--conf spark.task.resource.gpu.amount=0.01 \
--conf spark.executor.resource.gpu.amount=1 \
--conf spark.plugins=com.nvidia.spark.SQLPlugin \
--conf spark.rapids.sql.concurrentGpuTasks=2 \
--conf spark.rapids.sql.reader.batchSizeRows=4000000 \
--conf spark.rapids.memory.pinnedPool.size=16g \
--conf spark.rapids.sql.explain=ALL \
--conf spark.sql.autoBroadcastJoinThreshold=1GB \
--conf spark.rapids.sql.incompatibleOps.enabled=true \
--conf spark.driver.maxResultSize=2G \
--conf spark.executor.extraJavaOptions="-Dcom.nvidia.cudf.prefer-pinned=true\ -Djava.io.tmpdir=$SPARK_LOCAL_DIRS" \
spark_data_utils.py --mode transform \
--input_folder $INPUT_PATH \
--days 0-22 \
--output_folder $OUTPUT_PATH/train \
--model_size_file $OUTPUT_PATH/model_size.json \
--model_folder $OUTPUT_PATH/models \
--write_mode overwrite --low_mem 2>&1 | tee submit_train_log.txt
echo "Splitting the last day into 2 parts of test and validation..."
last_day=$INPUT_PATH/day_23
temp_test=$OUTPUT_PATH/temp/test
temp_validation=$OUTPUT_PATH/temp/validation
mkdir -p $temp_test $temp_validation
lines=`wc -l $last_day | awk '{print $1}'`
former=$((lines / 2))
latter=$((lines - former))
head -n $former $last_day > $temp_test/day_23
tail -n $latter $last_day > $temp_validation/day_23
echo "Transforming the test data in day_23..."
spark-submit --master $MASTER \
--driver-memory "${DRIVER_MEMORY}G" \
--executor-cores $NUM_EXECUTOR_CORES \
--executor-memory "${EXECUTOR_MEMORY}G" \
--conf spark.cores.max=$TOTAL_CORES \
--conf spark.task.cpus=1 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--conf spark.sql.shuffle.partitions=30 \
--conf spark.driver.maxResultSize=2G \
--conf spark.locality.wait=0s \
--conf spark.network.timeout=1800s \
--conf spark.task.resource.gpu.amount=0.01 \
--conf spark.executor.resource.gpu.amount=1 \
--conf spark.plugins=com.nvidia.spark.SQLPlugin \
--conf spark.rapids.sql.concurrentGpuTasks=2 \
--conf spark.rapids.sql.reader.batchSizeRows=4000000 \
--conf spark.rapids.memory.pinnedPool.size=16g \
--conf spark.rapids.sql.explain=ALL \
--conf spark.sql.autoBroadcastJoinThreshold=1GB \
--conf spark.rapids.sql.incompatibleOps.enabled=true \
--conf spark.driver.maxResultSize=2G \
--conf spark.executor.extraJavaOptions="-Dcom.nvidia.cudf.prefer-pinned=true\ -Djava.io.tmpdir=$SPARK_LOCAL_DIRS" \
spark_data_utils.py --mode transform \
--input_folder $temp_test \
--days 23-23 \
--output_folder $OUTPUT_PATH/test \
--output_ordering input \
--model_folder $OUTPUT_PATH/models \
--write_mode overwrite --low_mem 2>&1 | tee submit_test_log.txt
echo "Transforming the validation data in day_23..."
spark-submit --master $MASTER \
--driver-memory "${DRIVER_MEMORY}G" \
--executor-cores $NUM_EXECUTOR_CORES \
--executor-memory "${EXECUTOR_MEMORY}G" \
--conf spark.cores.max=$TOTAL_CORES \
--conf spark.task.cpus=1 \
--conf spark.sql.files.maxPartitionBytes=1073741824 \
--conf spark.sql.shuffle.partitions=30 \
--conf spark.driver.maxResultSize=2G \
--conf spark.locality.wait=0s \
--conf spark.network.timeout=1800s \
--conf spark.task.resource.gpu.amount=0.01 \
--conf spark.executor.resource.gpu.amount=1 \
--conf spark.plugins=com.nvidia.spark.SQLPlugin \
--conf spark.rapids.sql.concurrentGpuTasks=2 \
--conf spark.rapids.sql.reader.batchSizeRows=4000000 \
--conf spark.rapids.memory.pinnedPool.size=16g \
--conf spark.rapids.sql.explain=ALL \
--conf spark.sql.autoBroadcastJoinThreshold=1GB \
--conf spark.rapids.sql.incompatibleOps.enabled=true \
--conf spark.driver.maxResultSize=2G \
--conf spark.executor.extraJavaOptions="-Dcom.nvidia.cudf.prefer-pinned=true\ -Djava.io.tmpdir=$SPARK_LOCAL_DIRS" \
spark_data_utils.py --mode transform \
--input_folder $temp_validation \
--days 23-23 \
--output_folder $OUTPUT_PATH/validation \
--output_ordering input \
--model_folder $OUTPUT_PATH/models \
--write_mode overwrite --low_mem 2>&1 | tee submit_validation_log.txt
rm -r $temp_test $temp_validation
stop-master.sh
stop-slave.sh
|
PyTorch/SpeechSynthesis/HiFiGAN | HiFiGAN | .gitignore | results*/
output*
pretrained_models/
tb_*/
data/LJSpeech-1.1*
*.pyc
__pycache__
.idea/
.DS_Store
*.swp
*.swo
*.swn
|
PyTorch/Recommendation/DLRM/triton | triton | deployer_lib | #!/usr/bin/python
# Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import shutil
import time
import json
import onnx
import torch
import argparse
import statistics
import onnxruntime
from collections import Counter
torch_type_to_triton_type = {
torch.bool: 'TYPE_BOOL',
torch.int8: 'TYPE_INT8',
torch.int16: 'TYPE_INT16',
torch.int32: 'TYPE_INT32',
torch.int64: 'TYPE_INT64',
torch.uint8: 'TYPE_UINT8',
torch.float16: 'TYPE_FP16',
torch.float32: 'TYPE_FP32',
torch.float64: 'TYPE_FP64'
}
CONFIG_TEMPLATE = r"""
name: "{model_name}"
platform: "{platform}"
max_batch_size: {max_batch_size}
input [
{spec_inputs}
]
output [
{spec_outputs}
]
{dynamic_batching}
{model_optimizations}
instance_group [
{{
count: {engine_count}
kind: {kind}
gpus: [ {gpu_list} ]
}}
]
"""
INPUT_TEMPLATE = r"""
{{
name: "input__{num}"
data_type: {type}
dims: {dims}
{reshape}
}},"""
OUTPUT_TEMPLATE = r"""
{{
name: "output__{num}"
data_type: {type}
dims: {dims}
{reshape}
}},"""
MODEL_OPTIMIZATION_TEMPLATE = r"""
optimization {{
execution_accelerators {{
gpu_execution_accelerator: [
{{
name: "tensorrt"
}}
]
}}
}}
"""
def remove_empty_lines(text):
''' removes empty lines from text, returns the result '''
ret = "".join([s for s in text.strip().splitlines(True) if s.strip()])
return ret
def create_deployer(argv, model_args_parser):
''' takes a list of arguments, returns a deployer object and the list of unused arguments '''
parser = argparse.ArgumentParser()
# required args
method = parser.add_mutually_exclusive_group(required=True)
method.add_argument('--ts-script',
action='store_true',
help='convert to torchscript using torch.jit.script')
method.add_argument('--ts-trace',
action='store_true',
help='convert to torchscript using torch.jit.trace')
method.add_argument('--onnx',
action='store_true',
help='convert to onnx using torch.onnx.export')
# triton related args
arguments = parser.add_argument_group('triton related flags')
arguments.add_argument('--triton-no-cuda',
action='store_true',
help='Use the CPU for tracing.')
arguments.add_argument(
'--triton-model-name',
type=str,
default="model",
help="exports to appropriate directory structure for triton")
arguments.add_argument(
"--triton-model-version",
type=int,
default=1,
help="exports to appropriate directory structure for triton")
arguments.add_argument(
"--triton-max-batch-size",
type=int,
default=8,
help="Specifies the 'max_batch_size' in the triton model config.\
See the triton documentation for more info.")
arguments.add_argument(
"--triton-dyn-batching-delay",
type=float,
default=0,
help=
"Determines the dynamic_batching queue delay in milliseconds(ms) for\
the triton model config. Use '0' or '-1' to specify static batching.\
See the triton documentation for more info.")
arguments.add_argument(
"--triton-engine-count",
type=int,
default=1,
help=
"Specifies the 'instance_group' count value in the triton model config.\
See the triton documentation for more info.")
arguments.add_argument('--save-dir',
type=str,
default='./triton_models',
help='Saved model directory')
parser.add_argument("--deploy_cpu", default=False, action="store_true")
# other args
arguments = parser.add_argument_group('other flags')
# remainder args
arguments.add_argument(
'model_arguments',
nargs=argparse.REMAINDER,
help=
'arguments that will be ignored by deployer lib and will be forwarded to your deployer script'
)
#
args = parser.parse_args(argv)
model_args = model_args_parser(args.model_arguments[1:])
model_args_no_def = {
k: v
for k, v in vars(model_args).items()
if k in [arg[2:] for arg in args.model_arguments[1:]]
}
deployer = Deployer(args, model_args_no_def)
#
return deployer, model_args
class DeployerLibrary:
def __init__(self, args, model_args):
self.args = args
self.model_args = model_args
self.platform = None
def set_platform(self, platform):
''' sets the platform
:: platform :: "pytorch_libtorch" or "onnxruntime_onnx"
'''
self.platform = platform
def prepare_inputs(self, dataloader, device):
''' load sample inputs to device '''
inputs = []
for batch in dataloader:
if type(batch) is torch.Tensor:
batch_d = batch.to(device)
batch_d = (batch_d, )
inputs.append(batch_d)
else:
batch_d = []
for x in batch:
assert type(x) is torch.Tensor, "input is not a tensor"
batch_d.append(x.to(device) if device else x)
batch_d = tuple(batch_d)
inputs.append(batch_d)
return inputs
def get_list_of_shapes(self, l, fun):
''' returns the list of min/max shapes, depending on fun
:: l :: list of tuples of tensors
:: fun :: min or max
'''
tensor_tuple = l[0]
shapes = [list(x.shape) for x in tensor_tuple]
for tensor_tuple in l:
assert len(tensor_tuple) == len(
shapes), "tensors with varying shape lengths are not supported"
for i, x in enumerate(tensor_tuple):
for j in range(len(x.shape)):
shapes[i][j] = fun(shapes[i][j], x.shape[j])
return shapes # a list of shapes
def get_tuple_of_min_shapes(self, l):
''' returns the tuple of min shapes
:: l :: list of tuples of tensors '''
shapes = self.get_list_of_shapes(l, min)
min_batch = 1
shapes = [[min_batch, *shape[1:]] for shape in shapes]
shapes = tuple(shapes)
return shapes # tuple of min shapes
def get_tuple_of_max_shapes(self, l):
''' returns the tuple of max shapes
:: l :: list of tuples of tensors '''
shapes = self.get_list_of_shapes(l, max)
max_batch = max(2, shapes[0][0])
shapes = [[max_batch, *shape[1:]] for shape in shapes]
shapes = tuple(shapes)
return shapes # tuple of max shapes
def get_tuple_of_opt_shapes(self, l):
''' returns the tuple of opt shapes
:: l :: list of tuples of tensors '''
counter = Counter()
for tensor_tuple in l:
shapes = [x.shape for x in tensor_tuple]
shapes = tuple(shapes)
counter[shapes] += 1
shapes = counter.most_common(1)[0][0]
return shapes # tuple of most common occuring shapes
def get_tuple_of_dynamic_shapes(self, l):
''' returns a tuple of dynamic shapes: variable tensor dimensions
(for ex. batch size) occur as -1 in the tuple
:: l :: list of tuples of tensors '''
tensor_tuple = l[0]
shapes = [list(x.shape) for x in tensor_tuple]
for tensor_tuple in l:
err_msg = "tensors with varying shape lengths are not supported"
assert len(tensor_tuple) == len(shapes), err_msg
for i, x in enumerate(tensor_tuple):
for j in range(len(x.shape)):
if shapes[i][j] != x.shape[j] or j == 0:
shapes[i][j] = -1
shapes = tuple(shapes)
return shapes # tuple of dynamic shapes
def run_models(self, models, inputs):
''' run the models on inputs, return the outputs and execution times '''
ret = []
for model in models:
torch.cuda.synchronize()
time_start = time.time()
outputs = []
for input in inputs:
with torch.no_grad():
output = model(*input)
if type(output) is torch.Tensor:
output = [output]
outputs.append(output)
torch.cuda.synchronize()
time_end = time.time()
t = time_end - time_start
ret.append(outputs)
ret.append(t)
return ret
def compute_errors(self, outputs_A, outputs_B):
''' returns the list of L_inf errors computed over every single output tensor '''
Linf_errors = []
for output_A, output_B in zip(outputs_A, outputs_B):
for x, y in zip(output_A, output_B):
error = (x - y).norm(float('inf')).item()
Linf_errors.append(error)
return Linf_errors
def print_errors(self, Linf_errors):
''' print various statistcs of Linf errors '''
print()
print("conversion correctness test results")
print("-----------------------------------")
print("maximal absolute error over dataset (L_inf): ",
max(Linf_errors))
print()
print("average L_inf error over output tensors: ",
statistics.mean(Linf_errors))
print("variance of L_inf error over output tensors: ",
statistics.variance(Linf_errors))
print("stddev of L_inf error over output tensors: ",
statistics.stdev(Linf_errors))
print()
def write_config(self,
config_filename,
input_shapes,
input_types,
output_shapes,
output_types):
''' writes triton config file
:: config_filename :: the file to write the config file into
:: input_shapes :: tuple of dynamic shapes of the input tensors
:: input_types :: tuple of torch types of the input tensors
:: output_shapes :: tuple of dynamic shapes of the output tensors
:: output_types :: tuple of torch types of the output tensors
'''
assert self.platform is not None, "error - platform is not set"
config_template = CONFIG_TEMPLATE
accelerator_template = MODEL_OPTIMIZATION_TEMPLATE
input_template = INPUT_TEMPLATE
spec_inputs = r""""""
for i,(shape,typ) in enumerate(zip(input_shapes,input_types)):
d = {
'num' : str(i),
'type': torch_type_to_triton_type[typ],
'dims': str([1]) if len(shape) == 1 else str(list(shape)[1:]) # first dimension is the batch size
}
d['reshape'] = 'reshape: { shape: [ ] }' if len(shape) == 1 else ''
spec_inputs += input_template.format_map(d)
spec_inputs = spec_inputs[:-1]
output_template = OUTPUT_TEMPLATE
spec_outputs = r""""""
for i,(shape,typ) in enumerate(zip(output_shapes,output_types)):
d = {
'num' : str(i),
'type': torch_type_to_triton_type[typ],
'dims': str([1]) if len(shape) == 1 else str(list(shape)[1:]) # first dimension is the batch size
}
d['reshape'] = 'reshape: { shape: [ ] }' if len(shape) == 1 else ''
spec_outputs += output_template.format_map(d)
spec_outputs = spec_outputs[:-1]
batching_str = ""
parameters_str = ""
max_batch_size = self.args.triton_max_batch_size
accelerator_str = ""
if (self.args.triton_dyn_batching_delay > 0):
# Use only full and half full batches
pref_batch_size = [int(max_batch_size / 2.0), max_batch_size]
batching_str = r"""
dynamic_batching {{
preferred_batch_size: [{0}]
max_queue_delay_microseconds: {1}
}}""".format(", ".join([str(x) for x in pref_batch_size]),
int(self.args.triton_dyn_batching_delay * 1000.0))
if self.platform == 'onnxruntime_onnx':
accelerator_str = accelerator_template.format_map({})
config_values = {
"model_name": self.args.triton_model_name,
"platform": self.platform,
"max_batch_size": max_batch_size,
"spec_inputs": spec_inputs,
"spec_outputs": spec_outputs,
"dynamic_batching": batching_str,
"model_parameters": parameters_str,
"model_optimizations": accelerator_str,
"gpu_list": "" if self.args.deploy_cpu else ", ".join([str(x) for x in range(torch.cuda.device_count())]),
"engine_count": self.args.triton_engine_count,
"kind": "KIND_CPU" if self.args.deploy_cpu else "KIND_GPU"
}
# write config
with open(config_filename, "w") as file:
final_config_str = config_template.format_map(config_values)
final_config_str = remove_empty_lines(final_config_str)
file.write(final_config_str)
class Deployer:
def __init__(self, args, model_args):
self.args = args
self.lib = DeployerLibrary(args, model_args)
def deploy(self, dataloader, model):
''' deploy the model and test for correctness with dataloader '''
if self.args.ts_script or self.args.ts_trace:
self.lib.set_platform("pytorch_libtorch")
print("deploying model " + self.args.triton_model_name +
" in format " + self.lib.platform)
self.to_triton_torchscript(dataloader, model)
elif self.args.onnx:
self.lib.set_platform("onnxruntime_onnx")
print("deploying model " + self.args.triton_model_name +
" in format " + self.lib.platform)
self.to_triton_onnx(dataloader, model)
else:
assert False, "error"
print("done")
def to_triton_onnx(self, dataloader, model):
''' export the model to onnx and test correctness on dataloader '''
model.eval()
assert not model.training, "internal error - model should be in eval() mode! "
# prepare inputs
inputs = self.lib.prepare_inputs(dataloader, device=None)
# generate outputs
outputs = []
for input in inputs:
with torch.no_grad():
output = model(*input)
if type(output) is torch.Tensor:
output = [output]
outputs.append(output)
# generate input shapes - dynamic tensor shape support
input_shapes = self.lib.get_tuple_of_dynamic_shapes(inputs)
# generate output shapes - dynamic tensor shape support
output_shapes = self.lib.get_tuple_of_dynamic_shapes(outputs)
# generate input types
input_types = [x.dtype for x in inputs[0]]
# generate output types
output_types = [x.dtype for x in outputs[0]]
# get input names
rng = range(len(input_types))
input_names = ["input__" + str(num) for num in rng]
# get output names
rng = range(len(output_types))
output_names = ["output__" + str(num) for num in rng]
# prepare save path
model_folder = os.path.join(self.args.save_dir, self.args.triton_model_name)
version_folder = os.path.join(model_folder, str(self.args.triton_model_version))
if not os.path.exists(version_folder):
os.makedirs(version_folder)
final_model_path = os.path.join(version_folder, 'model.onnx')
if not os.path.exists(final_model_path):
os.makedirs(final_model_path)
final_model_path = os.path.join(final_model_path, 'model.onnx')
# get indices of dynamic input and output shapes
dynamic_axes = {}
for input_name,input_shape in zip(input_names,input_shapes):
dynamic_axes[input_name] = [i for i,x in enumerate(input_shape) if x == -1]
for output_name,output_shape in zip(output_names,output_shapes):
dynamic_axes[output_name] = [i for i,x in enumerate(output_shape) if x == -1]
# export the model
assert not model.training, "internal error - model should be in eval() mode! "
with torch.no_grad():
torch.onnx.export(model, inputs[0], final_model_path, verbose=False,
input_names=input_names, output_names=output_names,
dynamic_axes=dynamic_axes, opset_version=11,
use_external_data_format=True)
config_filename = os.path.join(model_folder, "config.pbtxt")
self.lib.write_config(config_filename,
input_shapes, input_types,
output_shapes, output_types)
def to_triton_torchscript(self, dataloader, model):
''' export the model to torchscript and test correctness on dataloader '''
model.eval()
assert not model.training, "internal error - model should be in eval() mode! "
# prepare inputs
inputs = self.lib.prepare_inputs(dataloader, device=None)
# generate input shapes - dynamic tensor shape support
input_shapes = self.lib.get_tuple_of_dynamic_shapes(inputs)
# generate input types
input_types = [x.dtype for x in inputs[0]]
# prepare save path
model_folder = os.path.join(self.args.save_dir, self.args.triton_model_name)
version_folder = os.path.join(model_folder, str(self.args.triton_model_version))
if not os.path.exists(version_folder):
os.makedirs(version_folder)
final_model_path = os.path.join(version_folder, 'model.pt')
# convert the model
with torch.no_grad():
if self.args.ts_trace: # trace it
model_ts = torch.jit.trace(model, inputs[0])
if self.args.ts_script: # script it
model_ts = torch.jit.script(model)
# generate outputs
outputs = []
for input in inputs:
with torch.no_grad():
output = model(*input)
if type(output) is torch.Tensor:
output = [output]
outputs.append(output)
# save the model
torch.jit.save(model_ts, final_model_path)
# generate output shapes - dynamic tensor shape support
output_shapes = self.lib.get_tuple_of_dynamic_shapes(outputs)
# generate output types
output_types = [x.dtype for x in outputs[0]]
# now we build the config for triton
config_filename = os.path.join(model_folder, "config.pbtxt")
self.lib.write_config(config_filename,
input_shapes, input_types,
output_shapes, output_types)
|
TensorFlow/Detection/SSD/models/research/object_detection/models | models | ssd_mobilenet_v2_fpn_feature_extractor | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""SSD MobilenetV2 FPN Feature Extractor."""
import copy
import functools
import tensorflow as tf
from object_detection.meta_architectures import ssd_meta_arch
from object_detection.models import feature_map_generators
from object_detection.utils import context_manager
from object_detection.utils import ops
from object_detection.utils import shape_utils
from nets.mobilenet import mobilenet
from nets.mobilenet import mobilenet_v2
slim = tf.contrib.slim
# A modified config of mobilenet v2 that makes it more detection friendly.
def _create_modified_mobilenet_config():
conv_defs = copy.deepcopy(mobilenet_v2.V2_DEF)
conv_defs['spec'][-1] = mobilenet.op(
slim.conv2d, stride=1, kernel_size=[1, 1], num_outputs=256)
return conv_defs
class SSDMobileNetV2FpnFeatureExtractor(ssd_meta_arch.SSDFeatureExtractor):
"""SSD Feature Extractor using MobilenetV2 FPN features."""
def __init__(self,
is_training,
depth_multiplier,
min_depth,
pad_to_multiple,
conv_hyperparams_fn,
fpn_min_level=3,
fpn_max_level=7,
additional_layer_depth=256,
reuse_weights=None,
use_explicit_padding=False,
use_depthwise=False,
override_base_feature_extractor_hyperparams=False):
"""SSD FPN feature extractor based on Mobilenet v2 architecture.
Args:
is_training: whether the network is in training mode.
depth_multiplier: float depth multiplier for feature extractor.
min_depth: minimum feature extractor depth.
pad_to_multiple: the nearest multiple to zero pad the input height and
width dimensions to.
conv_hyperparams_fn: A function to construct tf slim arg_scope for conv2d
and separable_conv2d ops in the layers that are added on top of the base
feature extractor.
fpn_min_level: the highest resolution feature map to use in FPN. The valid
values are {2, 3, 4, 5} which map to MobileNet v2 layers
{layer_4, layer_7, layer_14, layer_19}, respectively.
fpn_max_level: the smallest resolution feature map to construct or use in
FPN. FPN constructions uses features maps starting from fpn_min_level
upto the fpn_max_level. In the case that there are not enough feature
maps in the backbone network, additional feature maps are created by
applying stride 2 convolutions until we get the desired number of fpn
levels.
additional_layer_depth: additional feature map layer channel depth.
reuse_weights: whether to reuse variables. Default is None.
use_explicit_padding: Whether to use explicit padding when extracting
features. Default is False.
use_depthwise: Whether to use depthwise convolutions. Default is False.
override_base_feature_extractor_hyperparams: Whether to override
hyperparameters of the base feature extractor with the one from
`conv_hyperparams_fn`.
"""
super(SSDMobileNetV2FpnFeatureExtractor, self).__init__(
is_training=is_training,
depth_multiplier=depth_multiplier,
min_depth=min_depth,
pad_to_multiple=pad_to_multiple,
conv_hyperparams_fn=conv_hyperparams_fn,
reuse_weights=reuse_weights,
use_explicit_padding=use_explicit_padding,
use_depthwise=use_depthwise,
override_base_feature_extractor_hyperparams=
override_base_feature_extractor_hyperparams)
self._fpn_min_level = fpn_min_level
self._fpn_max_level = fpn_max_level
self._additional_layer_depth = additional_layer_depth
self._conv_defs = None
if self._use_depthwise:
self._conv_defs = _create_modified_mobilenet_config()
def preprocess(self, resized_inputs):
"""SSD preprocessing.
Maps pixel values to the range [-1, 1].
Args:
resized_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
"""
return (2.0 / 255.0) * resized_inputs - 1.0
def extract_features(self, preprocessed_inputs):
"""Extract features from preprocessed inputs.
Args:
preprocessed_inputs: a [batch, height, width, channels] float tensor
representing a batch of images.
Returns:
feature_maps: a list of tensors where the ith tensor has shape
[batch, height_i, width_i, depth_i]
"""
preprocessed_inputs = shape_utils.check_min_image_dim(
33, preprocessed_inputs)
with tf.variable_scope('MobilenetV2', reuse=self._reuse_weights) as scope:
with slim.arg_scope(
mobilenet_v2.training_scope(is_training=None, bn_decay=0.9997)), \
slim.arg_scope(
[mobilenet.depth_multiplier], min_depth=self._min_depth):
with (slim.arg_scope(self._conv_hyperparams_fn())
if self._override_base_feature_extractor_hyperparams else
context_manager.IdentityContextManager()):
_, image_features = mobilenet_v2.mobilenet_base(
ops.pad_to_multiple(preprocessed_inputs, self._pad_to_multiple),
final_endpoint='layer_19',
depth_multiplier=self._depth_multiplier,
conv_defs=self._conv_defs,
use_explicit_padding=self._use_explicit_padding,
scope=scope)
depth_fn = lambda d: max(int(d * self._depth_multiplier), self._min_depth)
with slim.arg_scope(self._conv_hyperparams_fn()):
with tf.variable_scope('fpn', reuse=self._reuse_weights):
feature_blocks = [
'layer_4', 'layer_7', 'layer_14', 'layer_19'
]
base_fpn_max_level = min(self._fpn_max_level, 5)
feature_block_list = []
for level in range(self._fpn_min_level, base_fpn_max_level + 1):
feature_block_list.append(feature_blocks[level - 2])
fpn_features = feature_map_generators.fpn_top_down_feature_maps(
[(key, image_features[key]) for key in feature_block_list],
depth=depth_fn(self._additional_layer_depth),
use_depthwise=self._use_depthwise,
use_explicit_padding=self._use_explicit_padding)
feature_maps = []
for level in range(self._fpn_min_level, base_fpn_max_level + 1):
feature_maps.append(fpn_features['top_down_{}'.format(
feature_blocks[level - 2])])
last_feature_map = fpn_features['top_down_{}'.format(
feature_blocks[base_fpn_max_level - 2])]
# Construct coarse features
padding = 'VALID' if self._use_explicit_padding else 'SAME'
kernel_size = 3
for i in range(base_fpn_max_level + 1, self._fpn_max_level + 1):
if self._use_depthwise:
conv_op = functools.partial(
slim.separable_conv2d, depth_multiplier=1)
else:
conv_op = slim.conv2d
if self._use_explicit_padding:
last_feature_map = ops.fixed_padding(
last_feature_map, kernel_size)
last_feature_map = conv_op(
last_feature_map,
num_outputs=depth_fn(self._additional_layer_depth),
kernel_size=[kernel_size, kernel_size],
stride=2,
padding=padding,
scope='bottom_up_Conv2d_{}'.format(i - base_fpn_max_level + 19))
feature_maps.append(last_feature_map)
return feature_maps
|
PyTorch/SpeechSynthesis/Tacotron2/trtis_cpp/src/trt/tacotron2 | tacotron2 | encoderInstance | /*
* Copyright (c) 2019-2020, NVIDIA CORPORATION. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the NVIDIA CORPORATION nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NVIDIA CORPORATION BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "encoderInstance.h"
#include "cudaUtils.h"
#include "engineCache.h"
#include "trtUtils.h"
#include <cassert>
using namespace nvinfer1;
namespace tts
{
/******************************************************************************
* CONSTRUCTORS / DESTRUCTOR **************************************************
*****************************************************************************/
EncoderInstance::EncoderInstance(TRTPtr<ICudaEngine> engine) :
TimedObject("EncoderInstance::infer()"),
EngineDriver(std::move(engine)),
mBinding(),
mContext(getEngine().createExecutionContext()),
mInputLength(TRTUtils::getBindingDimension(getEngine(), INPUT_NAME, 1))
{
// do nothing
}
/******************************************************************************
* PUBLIC METHODS *************************************************************
*****************************************************************************/
void EncoderInstance::infer(cudaStream_t stream, const int batchSize, const int32_t* const inputDevice,
const float* const inputMaskDevice, const int32_t* const inputLengthDevice, float* const outputDevice,
float* const outputProcessedDevice)
{
startTiming();
const ICudaEngine& engine = mContext->getEngine();
mBinding.setBinding(engine, INPUT_NAME, inputDevice);
mBinding.setBinding(engine, INPUT_MASK_NAME, inputMaskDevice);
mBinding.setBinding(engine, INPUT_LENGTH_NAME, inputLengthDevice);
mBinding.setBinding(engine, OUTPUT_NAME, outputDevice);
mBinding.setBinding(engine, OUTPUT_PROCESSED_NAME, outputProcessedDevice);
if (!mContext->enqueue(batchSize, mBinding.getBindings(), stream, nullptr))
{
throw std::runtime_error("Failed to run encoding.");
}
CudaUtils::sync(stream);
stopTiming();
}
int EncoderInstance::getInputLength() const
{
return mInputLength;
}
int EncoderInstance::getNumDimensions() const
{
return TRTUtils::getBindingDimension(getEngine(), OUTPUT_NAME, 2);
}
int EncoderInstance::getNumProcessedDimensions() const
{
return TRTUtils::getBindingDimension(getEngine(), OUTPUT_PROCESSED_NAME, 1);
}
} // namespace tts
|
Tools/PyTorch/TimeSeriesPredictionPlatform/triton | triton | requirements | # Copyright (c) 2021-2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
model_navigator[pyt] @ git+https://github.com/triton-inference-server/model_navigator.git@v0.2.7#egg=model_navigator
natsort>=7.0.0
networkx==2.5
numpy
onnx>=1.8.0,<1.9.0
onnxruntime-gpu==1.8.1
pycuda>=2019.1.2
PyYAML>=5.2
tabulate>=0.8.7
tqdm>=4.44.1
polygraphy==0.36.2
|
TensorFlow/Detection/SSD/models/research/object_detection/meta_architectures | meta_architectures | ssd_meta_arch_test | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Tests for object_detection.meta_architectures.ssd_meta_arch."""
from absl.testing import parameterized
import numpy as np
import tensorflow as tf
from object_detection.meta_architectures import ssd_meta_arch
from object_detection.meta_architectures import ssd_meta_arch_test_lib
from object_detection.protos import model_pb2
from object_detection.utils import test_utils
slim = tf.contrib.slim
keras = tf.keras.layers
@parameterized.parameters(
{'use_keras': False},
{'use_keras': True},
)
class SsdMetaArchTest(ssd_meta_arch_test_lib.SSDMetaArchTestBase,
parameterized.TestCase):
def _create_model(
self,
apply_hard_mining=True,
normalize_loc_loss_by_codesize=False,
add_background_class=True,
random_example_sampling=False,
expected_loss_weights=model_pb2.DetectionModel().ssd.loss.NONE,
min_num_negative_samples=1,
desired_negative_sampling_ratio=3,
use_keras=False,
predict_mask=False,
use_static_shapes=False,
nms_max_size_per_class=5):
return super(SsdMetaArchTest, self)._create_model(
model_fn=ssd_meta_arch.SSDMetaArch,
apply_hard_mining=apply_hard_mining,
normalize_loc_loss_by_codesize=normalize_loc_loss_by_codesize,
add_background_class=add_background_class,
random_example_sampling=random_example_sampling,
expected_loss_weights=expected_loss_weights,
min_num_negative_samples=min_num_negative_samples,
desired_negative_sampling_ratio=desired_negative_sampling_ratio,
use_keras=use_keras,
predict_mask=predict_mask,
use_static_shapes=use_static_shapes,
nms_max_size_per_class=nms_max_size_per_class)
def test_preprocess_preserves_shapes_with_dynamic_input_image(
self, use_keras):
image_shapes = [(3, None, None, 3),
(None, 10, 10, 3),
(None, None, None, 3)]
model, _, _, _ = self._create_model(use_keras=use_keras)
for image_shape in image_shapes:
image_placeholder = tf.placeholder(tf.float32, shape=image_shape)
preprocessed_inputs, _ = model.preprocess(image_placeholder)
self.assertAllEqual(preprocessed_inputs.shape.as_list(), image_shape)
def test_preprocess_preserves_shape_with_static_input_image(self, use_keras):
def graph_fn(input_image):
model, _, _, _ = self._create_model(use_keras=use_keras)
return model.preprocess(input_image)
input_image = np.random.rand(2, 3, 3, 3).astype(np.float32)
preprocessed_inputs, _ = self.execute(graph_fn, [input_image])
self.assertAllEqual(preprocessed_inputs.shape, [2, 3, 3, 3])
def test_predict_result_shapes_on_image_with_dynamic_shape(self, use_keras):
batch_size = 3
image_size = 2
input_shapes = [(None, image_size, image_size, 3),
(batch_size, None, None, 3),
(None, None, None, 3)]
for input_shape in input_shapes:
tf_graph = tf.Graph()
with tf_graph.as_default():
model, num_classes, num_anchors, code_size = self._create_model(
use_keras=use_keras)
preprocessed_input_placeholder = tf.placeholder(tf.float32,
shape=input_shape)
prediction_dict = model.predict(
preprocessed_input_placeholder, true_image_shapes=None)
self.assertIn('box_encodings', prediction_dict)
self.assertIn('class_predictions_with_background', prediction_dict)
self.assertIn('feature_maps', prediction_dict)
self.assertIn('anchors', prediction_dict)
init_op = tf.global_variables_initializer()
with self.test_session(graph=tf_graph) as sess:
sess.run(init_op)
prediction_out = sess.run(prediction_dict,
feed_dict={
preprocessed_input_placeholder:
np.random.uniform(
size=(batch_size, 2, 2, 3))})
expected_box_encodings_shape_out = (batch_size, num_anchors, code_size)
expected_class_predictions_with_background_shape_out = (batch_size,
num_anchors,
num_classes + 1)
self.assertAllEqual(prediction_out['box_encodings'].shape,
expected_box_encodings_shape_out)
self.assertAllEqual(
prediction_out['class_predictions_with_background'].shape,
expected_class_predictions_with_background_shape_out)
def test_predict_result_shapes_on_image_with_static_shape(self, use_keras):
with tf.Graph().as_default():
_, num_classes, num_anchors, code_size = self._create_model(
use_keras=use_keras)
def graph_fn(input_image):
model, _, _, _ = self._create_model()
predictions = model.predict(input_image, true_image_shapes=None)
return (predictions['box_encodings'],
predictions['class_predictions_with_background'],
predictions['feature_maps'],
predictions['anchors'])
batch_size = 3
image_size = 2
channels = 3
input_image = np.random.rand(batch_size, image_size, image_size,
channels).astype(np.float32)
expected_box_encodings_shape = (batch_size, num_anchors, code_size)
expected_class_predictions_shape = (batch_size, num_anchors, num_classes+1)
(box_encodings, class_predictions, _, _) = self.execute(graph_fn,
[input_image])
self.assertAllEqual(box_encodings.shape, expected_box_encodings_shape)
self.assertAllEqual(class_predictions.shape,
expected_class_predictions_shape)
def test_postprocess_results_are_correct(self, use_keras):
batch_size = 2
image_size = 2
input_shapes = [(batch_size, image_size, image_size, 3),
(None, image_size, image_size, 3),
(batch_size, None, None, 3),
(None, None, None, 3)]
expected_boxes = [
[
[0, 0, .5, .5],
[0, .5, .5, 1],
[.5, 0, 1, .5],
[0, 0, 0, 0], # pruned prediction
[0, 0, 0, 0]
], # padding
[
[0, 0, .5, .5],
[0, .5, .5, 1],
[.5, 0, 1, .5],
[0, 0, 0, 0], # pruned prediction
[0, 0, 0, 0]
]
] # padding
expected_scores = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
expected_classes = [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
expected_num_detections = np.array([3, 3])
for input_shape in input_shapes:
tf_graph = tf.Graph()
with tf_graph.as_default():
model, _, _, _ = self._create_model(use_keras=use_keras)
input_placeholder = tf.placeholder(tf.float32, shape=input_shape)
preprocessed_inputs, true_image_shapes = model.preprocess(
input_placeholder)
prediction_dict = model.predict(preprocessed_inputs,
true_image_shapes)
detections = model.postprocess(prediction_dict, true_image_shapes)
self.assertIn('detection_boxes', detections)
self.assertIn('detection_scores', detections)
self.assertIn('detection_classes', detections)
self.assertIn('num_detections', detections)
init_op = tf.global_variables_initializer()
with self.test_session(graph=tf_graph) as sess:
sess.run(init_op)
detections_out = sess.run(detections,
feed_dict={
input_placeholder:
np.random.uniform(
size=(batch_size, 2, 2, 3))})
for image_idx in range(batch_size):
self.assertTrue(
test_utils.first_rows_close_as_set(
detections_out['detection_boxes'][image_idx].tolist(),
expected_boxes[image_idx]))
self.assertAllClose(detections_out['detection_scores'], expected_scores)
self.assertAllClose(detections_out['detection_classes'], expected_classes)
self.assertAllClose(detections_out['num_detections'],
expected_num_detections)
def test_loss_results_are_correct(self, use_keras):
with tf.Graph().as_default():
_, num_classes, num_anchors, _ = self._create_model(use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2]
model, _, _, _ = self._create_model(apply_hard_mining=False)
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list)
prediction_dict = model.predict(preprocessed_tensor,
true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (self._get_value_for_matching_key(loss_dict,
'Loss/localization_loss'),
self._get_value_for_matching_key(loss_dict,
'Loss/classification_loss'))
batch_size = 2
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.0
expected_classification_loss = (batch_size * num_anchors
* (num_classes+1) * np.log(2.0))
(localization_loss,
classification_loss) = self.execute(graph_fn, [preprocessed_input,
groundtruth_boxes1,
groundtruth_boxes2,
groundtruth_classes1,
groundtruth_classes2])
self.assertAllClose(localization_loss, expected_localization_loss)
self.assertAllClose(classification_loss, expected_classification_loss)
def test_loss_results_are_correct_with_normalize_by_codesize_true(
self, use_keras):
with tf.Graph().as_default():
_, _, _, _ = self._create_model(use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2]
model, _, _, _ = self._create_model(apply_hard_mining=False,
normalize_loc_loss_by_codesize=True,
use_keras=use_keras)
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list)
prediction_dict = model.predict(preprocessed_tensor,
true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (self._get_value_for_matching_key(loss_dict,
'Loss/localization_loss'),)
batch_size = 2
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, 1, 1]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, 1, 1]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.5 / 4
localization_loss = self.execute(graph_fn, [preprocessed_input,
groundtruth_boxes1,
groundtruth_boxes2,
groundtruth_classes1,
groundtruth_classes2])
self.assertAllClose(localization_loss, expected_localization_loss)
def test_loss_results_are_correct_with_hard_example_mining(self, use_keras):
with tf.Graph().as_default():
_, num_classes, num_anchors, _ = self._create_model(use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2]
model, _, _, _ = self._create_model()
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list)
prediction_dict = model.predict(preprocessed_tensor,
true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (self._get_value_for_matching_key(loss_dict,
'Loss/localization_loss'),
self._get_value_for_matching_key(loss_dict,
'Loss/classification_loss'))
batch_size = 2
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.0
expected_classification_loss = (batch_size * num_anchors
* (num_classes+1) * np.log(2.0))
(localization_loss, classification_loss) = self.execute_cpu(
graph_fn, [
preprocessed_input, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2
])
self.assertAllClose(localization_loss, expected_localization_loss)
self.assertAllClose(classification_loss, expected_classification_loss)
def test_loss_results_are_correct_without_add_background_class(
self, use_keras):
with tf.Graph().as_default():
_, num_classes, num_anchors, _ = self._create_model(
add_background_class=False, use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2]
model, _, _, _ = self._create_model(
apply_hard_mining=False, add_background_class=False,
use_keras=use_keras)
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list)
prediction_dict = model.predict(
preprocessed_tensor, true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (loss_dict['Loss/localization_loss'],
loss_dict['Loss/classification_loss'])
batch_size = 2
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.0
expected_classification_loss = (
batch_size * num_anchors * num_classes * np.log(2.0))
(localization_loss, classification_loss) = self.execute(
graph_fn, [
preprocessed_input, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2
])
self.assertAllClose(localization_loss, expected_localization_loss)
self.assertAllClose(classification_loss, expected_classification_loss)
def test_loss_results_are_correct_with_losses_mask(self, use_keras):
with tf.Graph().as_default():
_, num_classes, num_anchors, _ = self._create_model(use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_boxes3, groundtruth_classes1, groundtruth_classes2,
groundtruth_classes3):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2,
groundtruth_boxes3]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2,
groundtruth_classes3]
is_annotated_list = [tf.constant(True), tf.constant(True),
tf.constant(False)]
model, _, _, _ = self._create_model(apply_hard_mining=False)
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list,
is_annotated_list=is_annotated_list)
prediction_dict = model.predict(preprocessed_tensor,
true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (self._get_value_for_matching_key(loss_dict,
'Loss/localization_loss'),
self._get_value_for_matching_key(loss_dict,
'Loss/classification_loss'))
batch_size = 3
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes3 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
groundtruth_classes3 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.0
# Note that we are subtracting 1 from batch_size, since the final image is
# not annotated.
expected_classification_loss = ((batch_size - 1) * num_anchors
* (num_classes+1) * np.log(2.0))
(localization_loss,
classification_loss) = self.execute(graph_fn, [preprocessed_input,
groundtruth_boxes1,
groundtruth_boxes2,
groundtruth_boxes3,
groundtruth_classes1,
groundtruth_classes2,
groundtruth_classes3])
self.assertAllClose(localization_loss, expected_localization_loss)
self.assertAllClose(classification_loss, expected_classification_loss)
def test_restore_map_for_detection_ckpt(self, use_keras):
model, _, _, _ = self._create_model(use_keras=use_keras)
model.predict(tf.constant(np.array([[[[0, 0], [1, 1]], [[1, 0], [0, 1]]]],
dtype=np.float32)),
true_image_shapes=None)
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
save_path = self.get_temp_dir()
with self.test_session() as sess:
sess.run(init_op)
saved_model_path = saver.save(sess, save_path)
var_map = model.restore_map(
fine_tune_checkpoint_type='detection',
load_all_detection_checkpoint_vars=False)
self.assertIsInstance(var_map, dict)
saver = tf.train.Saver(var_map)
saver.restore(sess, saved_model_path)
for var in sess.run(tf.report_uninitialized_variables()):
self.assertNotIn('FeatureExtractor', var)
def test_restore_map_for_classification_ckpt(self, use_keras):
# Define mock tensorflow classification graph and save variables.
test_graph_classification = tf.Graph()
with test_graph_classification.as_default():
image = tf.placeholder(dtype=tf.float32, shape=[1, 20, 20, 3])
if use_keras:
with tf.name_scope('mock_model'):
layer_one = keras.Conv2D(32, kernel_size=1, name='layer1')
net = layer_one(image)
layer_two = keras.Conv2D(3, kernel_size=1, name='layer2')
layer_two(net)
else:
with tf.variable_scope('mock_model'):
net = slim.conv2d(image, num_outputs=32, kernel_size=1,
scope='layer1')
slim.conv2d(net, num_outputs=3, kernel_size=1, scope='layer2')
init_op = tf.global_variables_initializer()
saver = tf.train.Saver()
save_path = self.get_temp_dir()
with self.test_session(graph=test_graph_classification) as sess:
sess.run(init_op)
saved_model_path = saver.save(sess, save_path)
# Create tensorflow detection graph and load variables from
# classification checkpoint.
test_graph_detection = tf.Graph()
with test_graph_detection.as_default():
model, _, _, _ = self._create_model(use_keras=use_keras)
inputs_shape = [2, 2, 2, 3]
inputs = tf.to_float(tf.random_uniform(
inputs_shape, minval=0, maxval=255, dtype=tf.int32))
preprocessed_inputs, true_image_shapes = model.preprocess(inputs)
prediction_dict = model.predict(preprocessed_inputs, true_image_shapes)
model.postprocess(prediction_dict, true_image_shapes)
another_variable = tf.Variable([17.0], name='another_variable') # pylint: disable=unused-variable
var_map = model.restore_map(fine_tune_checkpoint_type='classification')
self.assertNotIn('another_variable', var_map)
self.assertIsInstance(var_map, dict)
saver = tf.train.Saver(var_map)
with self.test_session(graph=test_graph_detection) as sess:
saver.restore(sess, saved_model_path)
for var in sess.run(tf.report_uninitialized_variables()):
self.assertNotIn('FeatureExtractor', var)
def test_load_all_det_checkpoint_vars(self, use_keras):
test_graph_detection = tf.Graph()
with test_graph_detection.as_default():
model, _, _, _ = self._create_model(use_keras=use_keras)
inputs_shape = [2, 2, 2, 3]
inputs = tf.to_float(
tf.random_uniform(inputs_shape, minval=0, maxval=255, dtype=tf.int32))
preprocessed_inputs, true_image_shapes = model.preprocess(inputs)
prediction_dict = model.predict(preprocessed_inputs, true_image_shapes)
model.postprocess(prediction_dict, true_image_shapes)
another_variable = tf.Variable([17.0], name='another_variable') # pylint: disable=unused-variable
var_map = model.restore_map(
fine_tune_checkpoint_type='detection',
load_all_detection_checkpoint_vars=True)
self.assertIsInstance(var_map, dict)
self.assertIn('another_variable', var_map)
def test_loss_results_are_correct_with_random_example_sampling(
self,
use_keras):
with tf.Graph().as_default():
_, num_classes, _, _ = self._create_model(
random_example_sampling=True, use_keras=use_keras)
def graph_fn(preprocessed_tensor, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2):
groundtruth_boxes_list = [groundtruth_boxes1, groundtruth_boxes2]
groundtruth_classes_list = [groundtruth_classes1, groundtruth_classes2]
model, _, _, _ = self._create_model(random_example_sampling=True,
use_keras=use_keras)
model.provide_groundtruth(groundtruth_boxes_list,
groundtruth_classes_list)
prediction_dict = model.predict(
preprocessed_tensor, true_image_shapes=None)
loss_dict = model.loss(prediction_dict, true_image_shapes=None)
return (self._get_value_for_matching_key(loss_dict,
'Loss/localization_loss'),
self._get_value_for_matching_key(loss_dict,
'Loss/classification_loss'))
batch_size = 2
preprocessed_input = np.random.rand(batch_size, 2, 2, 3).astype(np.float32)
groundtruth_boxes1 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_boxes2 = np.array([[0, 0, .5, .5]], dtype=np.float32)
groundtruth_classes1 = np.array([[1]], dtype=np.float32)
groundtruth_classes2 = np.array([[1]], dtype=np.float32)
expected_localization_loss = 0.0
# Among 4 anchors (1 positive, 3 negative) in this test, only 2 anchors are
# selected (1 positive, 1 negative) since random sampler will adjust number
# of negative examples to make sure positive example fraction in the batch
# is 0.5.
expected_classification_loss = (
batch_size * 2 * (num_classes + 1) * np.log(2.0))
(localization_loss, classification_loss) = self.execute_cpu(
graph_fn, [
preprocessed_input, groundtruth_boxes1, groundtruth_boxes2,
groundtruth_classes1, groundtruth_classes2
])
self.assertAllClose(localization_loss, expected_localization_loss)
self.assertAllClose(classification_loss, expected_classification_loss)
if __name__ == '__main__':
tf.test.main()
|
PyTorch/SpeechSynthesis/HiFiGAN/common/text | text | cleaners | """ adapted from https://github.com/keithito/tacotron """
'''
Cleaners are transformations that run over the input text at both training and eval time.
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
1. "english_cleaners" for English text
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
the symbols in symbols.py to match your data).
'''
import re
from .abbreviations import normalize_abbreviations
from .acronyms import normalize_acronyms, spell_acronyms
from .datestime import normalize_datestime
from .letters_and_numbers import normalize_letters_and_numbers
from .numerical import normalize_numbers
from .unidecoder import unidecoder
# Regular expression matching whitespace:
_whitespace_re = re.compile(r'\s+')
def expand_abbreviations(text):
return normalize_abbreviations(text)
def expand_numbers(text):
return normalize_numbers(text)
def expand_acronyms(text):
return normalize_acronyms(text)
def expand_datestime(text):
return normalize_datestime(text)
def expand_letters_and_numbers(text):
return normalize_letters_and_numbers(text)
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, ' ', text)
def separate_acronyms(text):
text = re.sub(r"([0-9]+)([a-zA-Z]+)", r"\1 \2", text)
text = re.sub(r"([a-zA-Z]+)([0-9]+)", r"\1 \2", text)
return text
def convert_to_ascii(text):
return unidecoder(text)
def basic_cleaners(text):
'''Basic pipeline that collapses whitespace without transliteration.'''
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
'''Pipeline for non-English text that transliterates to ASCII.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text):
'''Pipeline for English text, with number and abbreviation expansion.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
text = collapse_whitespace(text)
return text
def english_cleaners_v2(text):
text = convert_to_ascii(text)
text = expand_datestime(text)
text = expand_letters_and_numbers(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
text = spell_acronyms(text)
text = lowercase(text)
text = collapse_whitespace(text)
# compatibility with basic_english symbol set
text = re.sub(r'/+', ' ', text)
return text
|
TensorFlow2/Detection/Efficientdet/scripts/D0 | D0 | convergence-AMP-8xV100-32G | #!/bin/bash
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
bs=64
ep=300
lr=0.7
wu=5
ema=0.9999
momentum=0.9
mkdir -p /tmp/convergence-AMP-8xV100-32G
curr_dt=`date +"%Y-%m-%d-%H-%M-%S"`
mpirun -np 8 --allow-run-as-root --bind-to none \
-map-by slot -x LD_LIBRARY_PATH -x PATH \
-mca pml ob1 -mca btl ^openib \
-x CUDA_VISIBLE_DEVICES=0,1,2,3,4,5,6,7 \
python3 train.py \
--training_mode=${training_mode:=traineval} \
--training_file_pattern=/workspace/coco/train-* \
--val_file_pattern=/workspace/coco/val-* \
--val_json_file=/workspace/coco/annotations/instances_val2017.json \
--model_name=efficientdet-d0 \
--model_dir=/tmp/convergence-AMP-8xV100-32G \
--backbone_init=/workspace/checkpoints/efficientnet-b0-joc \
--batch_size=$bs \
--eval_batch_size=$bs \
--num_epochs=$ep \
--use_xla=True \
--amp=True \
--lr=$lr \
--warmup_epochs=$wu \
--hparams="moving_average_decay=$ema,momentum=$momentum" \
2>&1 | tee /tmp/convergence-AMP-8xV100-32G/train-$curr_dt.log |
TensorFlow/Segmentation/UNet_Industrial/utils/hooks | hooks | __init__ | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==============================================================================
#
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ==============================================================================
from utils.hooks.profiler_hook import *
|
Tools/PyTorch/TimeSeriesPredictionPlatform/distributed_launcher/hydra_plugins | hydra_plugins | _core | # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import logging
from functools import partial
from pathlib import Path
from typing import Sequence
from omegaconf import DictConfig, open_dict
from hydra.types import HydraContext
from hydra.core.singleton import Singleton
from hydra.core.hydra_config import HydraConfig
from hydra.types import TaskFunction
from hydra.core.utils import (
JobReturn,
configure_log,
filter_overrides,
run_job,
setup_globals,
env_override,
)
from torch.distributed.launcher.api import LaunchConfig, launch_agent
from torch.distributed.elastic.multiprocessing import Std
from .distributed_launcher import TorchDistributedLauncher
log = logging.getLogger(__name__)
def setup(
launcher: TorchDistributedLauncher,
*,
hydra_context: HydraContext,
task_function: TaskFunction,
config: DictConfig,
) -> None:
launcher.config = config
launcher.hydra_context = hydra_context
launcher.task_function = task_function
c = config.hydra.launcher
launcher.launch_config = LaunchConfig(
min_nodes=c.min_nodes,
max_nodes=c.max_nodes,
nproc_per_node=c.nproc_per_node,
run_id=c.rdzv_id,
role=c.role,
rdzv_endpoint=c.rdzv_endpoint,
rdzv_backend=c.rdzv_backend,
rdzv_configs={'rank': 0},
max_restarts=c.max_restarts,
monitor_interval=c.monitor_interval,
start_method='fork', # Works only with fork. Spawn and forkserver require pickling which does't work inside wrapped function
redirects=Std.from_str(c.redirects),
tee=Std.from_str(c.tee),
log_dir=c.get('log_dir'),
)
def launch(
launcher: TorchDistributedLauncher,
job_overrides: Sequence[Sequence[str]],
initial_job_idx: int
) -> Sequence[JobReturn]:
"""
:param job_overrides: a List of List<String>, where each inner list is the arguments for one job run.
:param initial_job_idx: Initial job idx in batch.
:return: an array of return values from run_job with indexes corresponding to the input list indexes.
"""
setup_globals()
assert launcher.config is not None
assert launcher.hydra_context is not None
assert launcher.task_function is not None
configure_log(launcher.config.hydra.hydra_logging, launcher.config.hydra.verbose)
sweep_dir = Path(str(launcher.config.hydra.sweep.dir))
sweep_dir.mkdir(parents=True, exist_ok=True)
runs = []
for idx, overrides in enumerate(job_overrides):
idx = initial_job_idx + idx
lst = " ".join(filter_overrides(overrides))
log.info(f"\t#{idx} : {lst}")
sweep_config = launcher.hydra_context.config_loader.load_sweep_config(
launcher.config, list(overrides)
)
with open_dict(sweep_config):
# This typically coming from the underlying scheduler (SLURM_JOB_ID for instance)
# In that case, it will not be available here because we are still in the main process.
# but instead should be populated remotely before calling the task_function.
sweep_config.hydra.job.id = f"job_id_for_{idx}"
sweep_config.hydra.job.num = idx
HydraConfig.instance().set_config(sweep_config)
launcher.singleton_state = Singleton.get_state()
def _task_function(task_function, singleton_state, task_cfg):
return launch_agent(launcher.launch_config,
wrapped_task_function,
[task_function, launcher.singleton_state, task_cfg]
)
_task_function = partial(_task_function, launcher.task_function, launcher.singleton_state)
ret = run_job(
hydra_context=launcher.hydra_context,
task_function=_task_function,
config=sweep_config,
job_dir_key="hydra.sweep.dir",
job_subdir_key="hydra.sweep.subdir",
)
# We assume that main process has rank 0
ret.return_value = ret.return_value[0]
runs.append(ret)
configure_log(launcher.config.hydra.hydra_logging, launcher.config.hydra.verbose)
return runs
def wrapped_task_function(task_function, singleton_state, task_cfg):
Singleton.set_state(singleton_state)
env_set = HydraConfig.instance().cfg.hydra.job.env_set
with env_override(env_set):
ret = task_function(task_cfg)
return ret
|
PyTorch/SpeechSynthesis/HiFiGAN/fastpitch | fastpitch | pitch_transform | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import torch
def pitch_transform_custom(pitch, pitch_lens):
"""Apply a custom pitch transformation to predicted pitch values.
This sample modification linearly increases the pitch throughout
the utterance from 0.5 of predicted pitch to 1.5 of predicted pitch.
In other words, it starts low and ends high.
PARAMS
------
pitch: torch.Tensor (bs, max_len)
Predicted pitch values for each lexical unit, padded to max_len (in Hz).
pitch_lens: torch.Tensor (bs, max_len)
Number of lexical units in each utterance.
RETURNS
-------
pitch: torch.Tensor
Modified pitch (in Hz).
"""
weights = torch.arange(pitch.size(1), dtype=torch.float32, device=pitch.device)
# The weights increase linearly from 0.0 to 1.0 in every i-th row
# in the range (0, pitch_lens[i])
weights = weights.unsqueeze(0) / pitch_lens.unsqueeze(1)
# Shift the range from (0.0, 1.0) to (0.5, 1.5)
weights += 0.5
return pitch * weights
|
TensorFlow2/Segmentation/Contrib/UNet3P/data_generators | data_generators | README | Our code base support two types of data loaders.
- [Tensorflow Sequence Generator](#tensorflow-sequence-generator)
- [NVIDIA DALI Generator](#nvidia-dali-generator)
## [Tensorflow Sequence Generator](https://www.tensorflow.org/api_docs/python/tf/keras/utils/Sequence)
Sequence data generator is best suited for situations where we need
advanced control over sample generation or when simple data does not
fit into memory and must be loaded dynamically.
Our [sequence generator](./../data_generators/tf_data_generator.py) generates
dataset on multiple cores in real time and feed it right away to deep
learning model.
## [NVIDIA DALI Generator](https://docs.nvidia.com/deeplearning/dali/user-guide/docs/index.html)
The NVIDIA Data Loading Library (DALI) is a library for data loading and
pre-processing to accelerate deep learning applications. It provides a
collection of highly optimized building blocks for loading and processing
image, video and audio data. It can be used as a portable drop-in
replacement for built in data loaders and data iterators in popular deep
learning frameworks.
We've used [DALI Pipeline](./../data_generators/dali_data_generator.py) to directly load
data on `GPU`, which resulted in reduced latency and training time,
mitigating bottlenecks, by overlapping training and pre-processing. Our code
base also support's multi GPU data loading for DALI.
## Use Cases
For training and evaluation you can use both `TF Sequence` and `DALI` generator with multiple gpus, but for prediction
and inference benchmark we only support `TF Sequence` generator with single gpu support.
> Reminder: DALI is only supported on Linux platforms. For Windows, you can
> train using Sequence Generator. The code base will work without DALI
> installation too.
It's advised to use DALI only when you have large gpu memory to load both model
and training data at the same time.
Override `DATA_GENERATOR_TYPE` in config to change default generator type. Possible
options are `TF_GENERATOR` for Sequence generator and `DALI_GENERATOR` for DALI generator.
|
TensorFlow/LanguageModeling/BERT | BERT | modeling_test | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import json
import random
import re
import modeling
import six
import tensorflow as tf
class BertModelTest(tf.test.TestCase):
class BertModelTester(object):
def __init__(self,
parent,
batch_size=13,
seq_length=7,
is_training=True,
use_input_mask=True,
use_token_type_ids=True,
vocab_size=99,
hidden_size=32,
num_hidden_layers=5,
num_attention_heads=4,
intermediate_size=37,
hidden_act="gelu",
hidden_dropout_prob=0.1,
attention_probs_dropout_prob=0.1,
max_position_embeddings=512,
type_vocab_size=16,
initializer_range=0.02,
scope=None):
self.parent = parent
self.batch_size = batch_size
self.seq_length = seq_length
self.is_training = is_training
self.use_input_mask = use_input_mask
self.use_token_type_ids = use_token_type_ids
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.num_hidden_layers = num_hidden_layers
self.num_attention_heads = num_attention_heads
self.intermediate_size = intermediate_size
self.hidden_act = hidden_act
self.hidden_dropout_prob = hidden_dropout_prob
self.attention_probs_dropout_prob = attention_probs_dropout_prob
self.max_position_embeddings = max_position_embeddings
self.type_vocab_size = type_vocab_size
self.initializer_range = initializer_range
self.scope = scope
def create_model(self):
input_ids = BertModelTest.ids_tensor([self.batch_size, self.seq_length],
self.vocab_size)
input_mask = None
if self.use_input_mask:
input_mask = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], vocab_size=2)
token_type_ids = None
if self.use_token_type_ids:
token_type_ids = BertModelTest.ids_tensor(
[self.batch_size, self.seq_length], self.type_vocab_size)
config = modeling.BertConfig(
vocab_size=self.vocab_size,
hidden_size=self.hidden_size,
num_hidden_layers=self.num_hidden_layers,
num_attention_heads=self.num_attention_heads,
intermediate_size=self.intermediate_size,
hidden_act=self.hidden_act,
hidden_dropout_prob=self.hidden_dropout_prob,
attention_probs_dropout_prob=self.attention_probs_dropout_prob,
max_position_embeddings=self.max_position_embeddings,
type_vocab_size=self.type_vocab_size,
initializer_range=self.initializer_range)
model = modeling.BertModel(
config=config,
is_training=self.is_training,
input_ids=input_ids,
input_mask=input_mask,
token_type_ids=token_type_ids,
scope=self.scope)
outputs = {
"embedding_output": model.get_embedding_output(),
"sequence_output": model.get_sequence_output(),
"pooled_output": model.get_pooled_output(),
"all_encoder_layers": model.get_all_encoder_layers(),
}
return outputs
def check_output(self, result):
self.parent.assertAllEqual(
result["embedding_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(
result["sequence_output"].shape,
[self.batch_size, self.seq_length, self.hidden_size])
self.parent.assertAllEqual(result["pooled_output"].shape,
[self.batch_size, self.hidden_size])
def test_default(self):
self.run_tester(BertModelTest.BertModelTester(self))
def test_config_to_json_string(self):
config = modeling.BertConfig(vocab_size=99, hidden_size=37)
obj = json.loads(config.to_json_string())
self.assertEqual(obj["vocab_size"], 99)
self.assertEqual(obj["hidden_size"], 37)
def run_tester(self, tester):
with self.test_session() as sess:
ops = tester.create_model()
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
sess.run(init_op)
output_result = sess.run(ops)
tester.check_output(output_result)
self.assert_all_tensors_reachable(sess, [init_op, ops])
@classmethod
def ids_tensor(cls, shape, vocab_size, rng=None, name=None):
"""Creates a random int32 tensor of the shape within the vocab size."""
if rng is None:
rng = random.Random()
total_dims = 1
for dim in shape:
total_dims *= dim
values = []
for _ in range(total_dims):
values.append(rng.randint(0, vocab_size - 1))
return tf.constant(value=values, dtype=tf.int32, shape=shape, name=name)
def assert_all_tensors_reachable(self, sess, outputs):
"""Checks that all the tensors in the graph are reachable from outputs."""
graph = sess.graph
ignore_strings = [
"^.*/assert_less_equal/.*$",
"^.*/dilation_rate$",
"^.*/Tensordot/concat$",
"^.*/Tensordot/concat/axis$",
"^testing/.*$",
]
ignore_regexes = [re.compile(x) for x in ignore_strings]
unreachable = self.get_unreachable_ops(graph, outputs)
filtered_unreachable = []
for x in unreachable:
do_ignore = False
for r in ignore_regexes:
m = r.match(x.name)
if m is not None:
do_ignore = True
if do_ignore:
continue
filtered_unreachable.append(x)
unreachable = filtered_unreachable
self.assertEqual(
len(unreachable), 0, "The following ops are unreachable: %s" %
(" ".join([x.name for x in unreachable])))
@classmethod
def get_unreachable_ops(cls, graph, outputs):
"""Finds all of the tensors in graph that are unreachable from outputs."""
outputs = cls.flatten_recursive(outputs)
output_to_op = collections.defaultdict(list)
op_to_all = collections.defaultdict(list)
assign_out_to_in = collections.defaultdict(list)
for op in graph.get_operations():
for x in op.inputs:
op_to_all[op.name].append(x.name)
for y in op.outputs:
output_to_op[y.name].append(op.name)
op_to_all[op.name].append(y.name)
if str(op.type) == "Assign":
for y in op.outputs:
for x in op.inputs:
assign_out_to_in[y.name].append(x.name)
assign_groups = collections.defaultdict(list)
for out_name in assign_out_to_in.keys():
name_group = assign_out_to_in[out_name]
for n1 in name_group:
assign_groups[n1].append(out_name)
for n2 in name_group:
if n1 != n2:
assign_groups[n1].append(n2)
seen_tensors = {}
stack = [x.name for x in outputs]
while stack:
name = stack.pop()
if name in seen_tensors:
continue
seen_tensors[name] = True
if name in output_to_op:
for op_name in output_to_op[name]:
if op_name in op_to_all:
for input_name in op_to_all[op_name]:
if input_name not in stack:
stack.append(input_name)
expanded_names = []
if name in assign_groups:
for assign_name in assign_groups[name]:
expanded_names.append(assign_name)
for expanded_name in expanded_names:
if expanded_name not in stack:
stack.append(expanded_name)
unreachable_ops = []
for op in graph.get_operations():
is_unreachable = False
all_names = [x.name for x in op.inputs] + [x.name for x in op.outputs]
for name in all_names:
if name not in seen_tensors:
is_unreachable = True
if is_unreachable:
unreachable_ops.append(op)
return unreachable_ops
@classmethod
def flatten_recursive(cls, item):
"""Flattens (potentially nested) a tuple/dictionary/list to a list."""
output = []
if isinstance(item, list):
output.extend(item)
elif isinstance(item, tuple):
output.extend(list(item))
elif isinstance(item, dict):
for (_, v) in six.iteritems(item):
output.append(v)
else:
return [item]
flat_output = []
for x in output:
flat_output.extend(cls.flatten_recursive(x))
return flat_output
if __name__ == "__main__":
tf.test.main()
|
PyTorch/SpeechRecognition/wav2vec2/scripts | scripts | pretrain_large | #!/usr/bin/env bash
# Copyright (c) 2023, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Pre-trains a LARGE model on LibriSpeech
set -e
export OMP_NUM_THREADS=1
export CUDNN_V8_API_ENABLED=1 # For older containers (~22.01)
export TORCH_CUDNN_V8_API_ENABLED=1
# IO
: ${DATASET_DIR:="/datasets/LibriSpeech"}
: ${TRAIN_SUBSET:="train-full-960"}
: ${VALID_SUBSET:="dev-other"}
: ${OUTPUT_DIR:="results/pretrain_large"}
# Batching
# To best utilize hw, increase batch size by increasing NUM_CONCAT_BATCHES, and lowering UPDATE_FREQ.
# Keep NUM_NODES x $NUM_GPUS x $NUM_CONCAT_BATCHES x $UPDATE_FREQ = 128.
# Note that this script does not control NUM_NODES.
: ${NUM_GPUS:=8}
: ${MAX_TOKENS:=1200000}
: ${NUM_CONCAT_BATCHES:=1}
: ${UPDATE_FREQ:=16}
: ${MIN_SAMPLE_SIZE:=32000}
: ${MAX_SAMPLE_SIZE:=320000}
# Training
# Fairseq 'Wav2Vec 2.0 Large (LV-60 + CV + SWBD + FSH)' model has been trained
# for 800k steps with 25.6k warmup (wav2vec2_large_librivox.yaml sets 1M/32k)
: ${MAX_UPDATE:=800000}
: ${WARMUP_UPDATES:=32000}
: ${OPTIMIZER:=adam}
: ${LEARNING_RATE:=0.005}
: ${LOSS_WEIGHTS:="0.1 0.0"}
: ${FP16:=false}
: ${BF16:=false}
: ${EMA:=0.0}
: ${SEED=""} # Disable seed - TODO check if it is working
: ${CUDNN_BENCHMARK:=false}
# Model
: ${NORMALIZE:=true}
: ${MASK_PROB:=0.65}
: ${EXTRACTOR_MODE:="layer_norm"}
: ${LAYER_NORM_FIRST:=true} # enabled in the `large` model
: ${FINAL_DIM:=768}
: ${LATENT_TEMP:="2.0 0.1 0.999995"}
: ${ENCODER_LAYERDROP:=0.0}
: ${DROPOUT_INPUT:=0.0}
: ${DROPOUT_FEATURES:=0.0}
: ${DROPOUT:=0.0}
: ${ATTENTION_DROPOUT:=0.0}
: ${CONV_BIAS:=true}
: ${ENCODER_LAYERS:=24}
: ${ENCODER_EMBED_DIM:=1024}
: ${ENCODER_FFN_EMBED_DIM:=4096}
: ${ENCODER_ATTENTION_HEADS:=16}
: ${FEATURE_GRAD_MULT:=1.0}
# Misc
: ${NO_SAVE:=false}
: ${SAVE_FREQUENCY=1}
: ${DISTRIBUTED="-m torch.distributed.launch --nproc_per_node=$NUM_GPUS"}
mkdir -p "$OUTPUT_DIR"
ARGS+=" --resume"
ARGS+=" --save_frequency $SAVE_FREQUENCY"
ARGS+=" --data $DATASET_DIR"
ARGS+=" --train_subset $TRAIN_SUBSET"
ARGS+=" --valid_subset $VALID_SUBSET"
ARGS+=" --output_dir $OUTPUT_DIR"
ARGS+=" --ema $EMA"
ARGS+=" --optimizer $OPTIMIZER"
ARGS+=" --lr $LEARNING_RATE"
ARGS+=" --clip_norm 25"
ARGS+=" --weight_decay 0.01"
ARGS+=" --lr_policy poly"
ARGS+=" --lr_poly_power 1.0"
ARGS+=" --loss_weights $LOSS_WEIGHTS"
ARGS+=" --warmup_updates $WARMUP_UPDATES"
ARGS+=" --max_update $MAX_UPDATE"
ARGS+=" --num_concat_batches $NUM_CONCAT_BATCHES"
ARGS+=" --update_freq $UPDATE_FREQ "
ARGS+=" --max_tokens $MAX_TOKENS"
ARGS+=" --max_tokens_valid $MAX_TOKENS"
ARGS+=" --skip_invalid_size_inputs_valid_test" # XXX ??? ??? ???
ARGS+=" --infonce"
ARGS+=" --min_sample_size $MIN_SAMPLE_SIZE"
ARGS+=" --max_sample_size $MAX_SAMPLE_SIZE"
ARGS+=" --mask_prob $MASK_PROB"
ARGS+=" --quantize_targets"
ARGS+=" --extractor_mode $EXTRACTOR_MODE"
ARGS+=" --final_dim $FINAL_DIM"
ARGS+=" --latent_temp $LATENT_TEMP"
ARGS+=" --encoder_layerdrop $ENCODER_LAYERDROP"
ARGS+=" --dropout_input $DROPOUT_INPUT"
ARGS+=" --dropout_features $DROPOUT_FEATURES"
ARGS+=" --dropout $DROPOUT"
ARGS+=" --attention_dropout $ATTENTION_DROPOUT"
ARGS+=" --encoder_layers $ENCODER_LAYERS"
ARGS+=" --encoder_embed_dim $ENCODER_EMBED_DIM"
ARGS+=" --encoder_ffn_embed_dim $ENCODER_FFN_EMBED_DIM"
ARGS+=" --encoder_attention_heads $ENCODER_ATTENTION_HEADS"
ARGS+=" --feature_grad_mult $FEATURE_GRAD_MULT"
ARGS+=" --mha pyt"
# float16
[ "$FP16" = true ] && ARGS+=" --fp16"
[ "$FP16" = true ] && ARGS+=" --fp32_cosine_sim"
[ "$FP16" = true ] && ARGS+=" --fp32_conv_norms"
[ "$FP16" = true ] && ARGS+=" --fp32_pos_conv"
# bfloat16
[ "$BF16" = true ] && ARGS+=" --bf16"
[ "$BF16" = true ] && ARGS+=" --fp32_pos_conv"
# Misc
[ "$NORMALIZE" = true ] && ARGS+=" --normalize"
[ "$CONV_BIAS" = true ] && ARGS+=" --conv_bias"
[ "$LAYER_NORM_FIRST" = true ] && ARGS+=" --layer_norm_first"
[ -n "$SEED" ] && ARGS+=" --seed $SEED"
[ -n "$EPOCHS_THIS_JOB" ] && ARGS+=" --epochs_this_job $EPOCHS_THIS_JOB"
[ "$CUDNN_BENCHMARK" = true ] && ARGS+=" --cudnn_benchmark"
[ "$FP32_TRANSFORMER_LAYERNORM" = true ] && ARGS+=" --fp32_transformer_layernorm"
[ "$FP32_MHA_SOFTMAX" = true ] && ARGS+=" --fp32_mha_softmax"
[ "$FP32_COSINE_SIM" = true ] && ARGS+=" --fp32_cosine_sim"
[ "$FP32_POS_CONV" = true ] && ARGS+=" --fp32_pos_conv"
[ "$FP32_CONV_NORMS" = true ] && ARGS+=" --fp32_conv_norms"
[ -n "$HOURGLASS_CONFIG" ] && ARGS+=" --hourglass_transformer $HOURGLASS_CONFIG"
[ "$NO_SAVE" = true ] && ARGS+=" --no_save"
echo -e "\nFP16=$FP16, BP16=$BF16, ${NUM_GPUS}x(${MAX_TOKENS}x${NUM_CONCAT_BATCHES})x${UPDATE_FREQ}\n"
set -x
python3 $DISTRIBUTED train.py pretrain $ARGS "$@"
|
PyTorch/Segmentation/nnUNet/triton/scripts | scripts | process_dataset | #!/usr/bin/env bash
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
python download.py --task 01 --results ${DATASETS_DIR}
python preprocess.py --task 01 --dim 3 --data ${DATASETS_DIR} --results ${DATASETS_DIR}
|
TensorFlow/Detection/SSD/models/research/slim/nets | nets | overfeat | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Contains the model definition for the OverFeat network.
The definition for the network was obtained from:
OverFeat: Integrated Recognition, Localization and Detection using
Convolutional Networks
Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and
Yann LeCun, 2014
http://arxiv.org/abs/1312.6229
Usage:
with slim.arg_scope(overfeat.overfeat_arg_scope()):
outputs, end_points = overfeat.overfeat(inputs)
@@overfeat
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
slim = tf.contrib.slim
trunc_normal = lambda stddev: tf.truncated_normal_initializer(0.0, stddev)
def overfeat_arg_scope(weight_decay=0.0005):
with slim.arg_scope([slim.conv2d, slim.fully_connected],
activation_fn=tf.nn.relu,
weights_regularizer=slim.l2_regularizer(weight_decay),
biases_initializer=tf.zeros_initializer()):
with slim.arg_scope([slim.conv2d], padding='SAME'):
with slim.arg_scope([slim.max_pool2d], padding='VALID') as arg_sc:
return arg_sc
def overfeat(inputs,
num_classes=1000,
is_training=True,
dropout_keep_prob=0.5,
spatial_squeeze=True,
scope='overfeat',
global_pool=False):
"""Contains the model definition for the OverFeat network.
The definition for the network was obtained from:
OverFeat: Integrated Recognition, Localization and Detection using
Convolutional Networks
Pierre Sermanet, David Eigen, Xiang Zhang, Michael Mathieu, Rob Fergus and
Yann LeCun, 2014
http://arxiv.org/abs/1312.6229
Note: All the fully_connected layers have been transformed to conv2d layers.
To use in classification mode, resize input to 231x231. To use in fully
convolutional mode, set spatial_squeeze to false.
Args:
inputs: a tensor of size [batch_size, height, width, channels].
num_classes: number of predicted classes. If 0 or None, the logits layer is
omitted and the input features to the logits layer are returned instead.
is_training: whether or not the model is being trained.
dropout_keep_prob: the probability that activations are kept in the dropout
layers during training.
spatial_squeeze: whether or not should squeeze the spatial dimensions of the
outputs. Useful to remove unnecessary dimensions for classification.
scope: Optional scope for the variables.
global_pool: Optional boolean flag. If True, the input to the classification
layer is avgpooled to size 1x1, for any input size. (This is not part
of the original OverFeat.)
Returns:
net: the output of the logits layer (if num_classes is a non-zero integer),
or the non-dropped-out input to the logits layer (if num_classes is 0 or
None).
end_points: a dict of tensors with intermediate activations.
"""
with tf.variable_scope(scope, 'overfeat', [inputs]) as sc:
end_points_collection = sc.original_name_scope + '_end_points'
# Collect outputs for conv2d, fully_connected and max_pool2d
with slim.arg_scope([slim.conv2d, slim.fully_connected, slim.max_pool2d],
outputs_collections=end_points_collection):
net = slim.conv2d(inputs, 64, [11, 11], 4, padding='VALID',
scope='conv1')
net = slim.max_pool2d(net, [2, 2], scope='pool1')
net = slim.conv2d(net, 256, [5, 5], padding='VALID', scope='conv2')
net = slim.max_pool2d(net, [2, 2], scope='pool2')
net = slim.conv2d(net, 512, [3, 3], scope='conv3')
net = slim.conv2d(net, 1024, [3, 3], scope='conv4')
net = slim.conv2d(net, 1024, [3, 3], scope='conv5')
net = slim.max_pool2d(net, [2, 2], scope='pool5')
# Use conv2d instead of fully_connected layers.
with slim.arg_scope([slim.conv2d],
weights_initializer=trunc_normal(0.005),
biases_initializer=tf.constant_initializer(0.1)):
net = slim.conv2d(net, 3072, [6, 6], padding='VALID', scope='fc6')
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout6')
net = slim.conv2d(net, 4096, [1, 1], scope='fc7')
# Convert end_points_collection into a end_point dict.
end_points = slim.utils.convert_collection_to_dict(
end_points_collection)
if global_pool:
net = tf.reduce_mean(net, [1, 2], keep_dims=True, name='global_pool')
end_points['global_pool'] = net
if num_classes:
net = slim.dropout(net, dropout_keep_prob, is_training=is_training,
scope='dropout7')
net = slim.conv2d(net, num_classes, [1, 1],
activation_fn=None,
normalizer_fn=None,
biases_initializer=tf.zeros_initializer(),
scope='fc8')
if spatial_squeeze:
net = tf.squeeze(net, [1, 2], name='fc8/squeezed')
end_points[sc.name + '/fc8'] = net
return net, end_points
overfeat.default_image_size = 231
|
PyTorch/SpeechRecognition/QuartzNet/common/text | text | cleaners | # Copyright (c) 2017 Keith Ito
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" from https://github.com/keithito/tacotron
Modified to add puncturation removal
"""
'''
Cleaners are transformations that run over the input text at both training and eval time.
Cleaners can be selected by passing a comma-delimited list of cleaner names as the "cleaners"
hyperparameter. Some cleaners are English-specific. You'll typically want to use:
1. "english_cleaners" for English text
2. "transliteration_cleaners" for non-English text that can be transliterated to ASCII using
the Unidecode library (https://pypi.python.org/pypi/Unidecode)
3. "basic_cleaners" if you do not want to transliterate (in this case, you should also update
the symbols in symbols.py to match your data).
'''
import re
from .numbers import normalize_numbers
from .unidecoder import unidecoder
# Regular expression matching whitespace:
_whitespace_re = re.compile(r'\s+')
# List of (regular expression, replacement) pairs for abbreviations:
_abbreviations = [(re.compile('\\b%s\\.' % x[0], re.IGNORECASE), x[1]) for x in [
('mrs', 'misess'),
('mr', 'mister'),
('dr', 'doctor'),
('st', 'saint'),
('co', 'company'),
('jr', 'junior'),
('maj', 'major'),
('gen', 'general'),
('drs', 'doctors'),
('rev', 'reverend'),
('lt', 'lieutenant'),
('hon', 'honorable'),
('sgt', 'sergeant'),
('capt', 'captain'),
('esq', 'esquire'),
('ltd', 'limited'),
('col', 'colonel'),
('ft', 'fort'),
]]
def expand_abbreviations(text):
for regex, replacement in _abbreviations:
text = re.sub(regex, replacement, text)
return text
def expand_numbers(text):
return normalize_numbers(text)
def lowercase(text):
return text.lower()
def collapse_whitespace(text):
return re.sub(_whitespace_re, ' ', text)
def convert_to_ascii(text):
return unidecoder(text)
def remove_punctuation(text, table):
text = text.translate(table)
text = re.sub(r'&', " and ", text)
text = re.sub(r'\+', " plus ", text)
return text
def basic_cleaners(text):
'''Basic pipeline that lowercases and collapses whitespace without transliteration.'''
text = lowercase(text)
text = collapse_whitespace(text)
return text
def transliteration_cleaners(text):
'''Pipeline for non-English text that transliterates to ASCII.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = collapse_whitespace(text)
return text
def english_cleaners(text, table=None):
'''Pipeline for English text, including number and abbreviation expansion.'''
text = convert_to_ascii(text)
text = lowercase(text)
text = expand_numbers(text)
text = expand_abbreviations(text)
if table is not None:
text = remove_punctuation(text, table)
text = collapse_whitespace(text)
return text
|
PyTorch/LanguageModeling/BERT/triton/dist4l/scripts | scripts | setup_parameters | #!/usr/bin/env bash
# Copyright (c) 2021 NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
echo "Setting up deployment parameters"
export FORMAT="onnx"
export PRECISION="fp16"
export EXPORT_FORMAT="onnx"
export EXPORT_PRECISION="fp16"
export ACCELERATOR="trt"
export ACCELERATOR_PRECISION="fp16"
export CAPTURE_CUDA_GRAPH="0"
export BATCH_SIZE="16"
export MAX_BATCH_SIZE="16"
export MAX_SEQ_LENGTH="384"
export CHECKPOINT_VARIANT="dist-4l-qa"
export CHECKPOINT_DIR=${CHECKPOINTS_DIR}/${CHECKPOINT_VARIANT}
export TRITON_MAX_QUEUE_DELAY="1"
export TRITON_GPU_ENGINE_COUNT="1"
export TRITON_PREFERRED_BATCH_SIZES="1"
if [[ "${FORMAT}" == "ts-trace" || "${FORMAT}" == "ts-script" ]]; then
export CONFIG_FORMAT="torchscript"
else
export CONFIG_FORMAT="${FORMAT}"
fi
if [[ "${EXPORT_FORMAT}" == "trt" ]]; then
export FLAG="--fixed-batch-dim"
else
export FLAG=""
fi
if [[ "${FORMAT}" == "ts-trace" || "${FORMAT}" == "ts-script" ]]; then
export CONFIG_FORMAT="torchscript"
else
export CONFIG_FORMAT="${FORMAT}"
fi
if [[ "${FORMAT}" == "trt" ]]; then
export MBS="0"
else
export MBS="${MAX_BATCH_SIZE}"
fi
if [[ "${EXPORT_FORMAT}" == "ts-trace" || "${EXPORT_FORMAT}" == "ts-script" ]]; then
export FORMAT_SUFFIX="pt"
else
export FORMAT_SUFFIX="${EXPORT_FORMAT}"
fi |
Tools/PyTorch/TimeSeriesPredictionPlatform/models/tft_pyt/triton/deployment_toolkit | deployment_toolkit | warmup | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import pathlib
from distutils.version import LooseVersion
from importlib.metadata import version
from typing import List
TRITON_CLIENT_VERSION = LooseVersion(version("tritonclient"))
# method from PEP-366 to support relative import in executed modules
if __package__ is None:
__package__ = pathlib.Path(__file__).parent.name
from .core import BatchingMode, EvaluationMode, MeasurementMode, OfflineMode
from .perf_analyzer import PerfAnalyzer, PerfAnalyzerConfig
from .utils import parse_server_url
LOGGER = logging.getLogger("warmup")
def performance_evaluation_warmup(
server_url: str,
model_name: str,
batch_sizes: List[int],
number_of_triton_instances: int,
number_of_model_instances: int,
input_data: str,
input_shapes: List[str],
measurement_mode: MeasurementMode,
measurement_interval: int,
measurement_request_count: int,
batching_mode: BatchingMode,
offline_mode: OfflineMode,
evaluation_mode: EvaluationMode,
output_shared_memory_size: int,
):
protocol, host, port = parse_server_url(server_url)
measurement_interval = 2 * measurement_interval
measurement_request_count = 2 * measurement_request_count
if batching_mode == BatchingMode.STATIC:
if len(batch_sizes) == 1:
batch_sizes = {batch_sizes[0]}
else:
batch_sizes = sorted({1, batch_sizes[-1]})
max_concurrency = 1
min_concurrency = 1
step = 1
elif batching_mode == BatchingMode.DYNAMIC:
max_batch_size = max(batch_sizes)
max_total_requests = 2 * max_batch_size * number_of_triton_instances * number_of_model_instances
max_concurrency = min(256, max_total_requests)
step = max(1, max_concurrency // 2)
min_concurrency = step
batch_sizes = [max(1, max_total_requests // 256)]
else:
raise ValueError(f"Unsupported batching mode: {batching_mode}")
for batch_size in batch_sizes:
for concurrency in range(min_concurrency, max_concurrency + step, step):
params = {
"model-name": model_name,
"model-version": 1,
"batch-size": batch_size,
"url": f"{host}:{port}",
"protocol": protocol,
"input-data": input_data,
"measurement-interval": measurement_interval,
"concurrency-range": f"{concurrency}:{concurrency}:1",
}
if TRITON_CLIENT_VERSION >= LooseVersion("2.11.0"):
params["measurement-mode"] = measurement_mode.value
params["measurement-request-count"] = measurement_request_count
if evaluation_mode == EvaluationMode.OFFLINE:
params["shared-memory"] = offline_mode.value
params["output-shared-memory-size"] = output_shared_memory_size
config = PerfAnalyzerConfig()
for param, value in params.items():
config[param] = value
for shape in input_shapes:
config["shape"] = shape
perf_analyzer = PerfAnalyzer(config=config)
perf_analyzer.run()
|
Tools/PyTorch/TimeSeriesPredictionPlatform/models/tft_pyt/triton | triton | requirements | # Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# model_navigator[pyt] @ git+https://github.com/triton-inference-server/model_navigator.git@v0.2.3#egg=model_navigator
model_navigator[pyt] @ git+https://github.com/triton-inference-server/model_navigator.git@v0.2.5#egg=model_navigator
natsort>=7.0.0
networkx==2.5
numpy
onnx>=1.8.0,<1.9.0
onnxruntime-gpu==1.8.1
pycuda>=2019.1.2
PyYAML>=5.2
tabulate>=0.8.7
tqdm>=4.44.1
|
TensorFlow/Detection/SSD/models/research/object_detection/utils | utils | config_util | # Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Functions for reading and updating configuration files."""
import os
import tensorflow as tf
from google.protobuf import text_format
from tensorflow.python.lib.io import file_io
from object_detection.protos import eval_pb2
from object_detection.protos import graph_rewriter_pb2
from object_detection.protos import input_reader_pb2
from object_detection.protos import model_pb2
from object_detection.protos import pipeline_pb2
from object_detection.protos import train_pb2
def get_image_resizer_config(model_config):
"""Returns the image resizer config from a model config.
Args:
model_config: A model_pb2.DetectionModel.
Returns:
An image_resizer_pb2.ImageResizer.
Raises:
ValueError: If the model type is not recognized.
"""
meta_architecture = model_config.WhichOneof("model")
if meta_architecture == "faster_rcnn":
return model_config.faster_rcnn.image_resizer
if meta_architecture == "ssd":
return model_config.ssd.image_resizer
raise ValueError("Unknown model type: {}".format(meta_architecture))
def get_spatial_image_size(image_resizer_config):
"""Returns expected spatial size of the output image from a given config.
Args:
image_resizer_config: An image_resizer_pb2.ImageResizer.
Returns:
A list of two integers of the form [height, width]. `height` and `width` are
set -1 if they cannot be determined during graph construction.
Raises:
ValueError: If the model type is not recognized.
"""
if image_resizer_config.HasField("fixed_shape_resizer"):
return [
image_resizer_config.fixed_shape_resizer.height,
image_resizer_config.fixed_shape_resizer.width
]
if image_resizer_config.HasField("keep_aspect_ratio_resizer"):
if image_resizer_config.keep_aspect_ratio_resizer.pad_to_max_dimension:
return [image_resizer_config.keep_aspect_ratio_resizer.max_dimension] * 2
else:
return [-1, -1]
raise ValueError("Unknown image resizer type.")
def get_configs_from_pipeline_file(pipeline_config_path, config_override=None):
"""Reads config from a file containing pipeline_pb2.TrainEvalPipelineConfig.
Args:
pipeline_config_path: Path to pipeline_pb2.TrainEvalPipelineConfig text
proto.
config_override: A pipeline_pb2.TrainEvalPipelineConfig text proto to
override pipeline_config_path.
Returns:
Dictionary of configuration objects. Keys are `model`, `train_config`,
`train_input_config`, `eval_config`, `eval_input_config`. Value are the
corresponding config objects.
"""
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.gfile.GFile(pipeline_config_path, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, pipeline_config)
if config_override:
text_format.Merge(config_override, pipeline_config)
return create_configs_from_pipeline_proto(pipeline_config)
def create_configs_from_pipeline_proto(pipeline_config):
"""Creates a configs dictionary from pipeline_pb2.TrainEvalPipelineConfig.
Args:
pipeline_config: pipeline_pb2.TrainEvalPipelineConfig proto object.
Returns:
Dictionary of configuration objects. Keys are `model`, `train_config`,
`train_input_config`, `eval_config`, `eval_input_configs`. Value are
the corresponding config objects or list of config objects (only for
eval_input_configs).
"""
configs = {}
configs["model"] = pipeline_config.model
configs["train_config"] = pipeline_config.train_config
configs["train_input_config"] = pipeline_config.train_input_reader
configs["eval_config"] = pipeline_config.eval_config
configs["eval_input_configs"] = pipeline_config.eval_input_reader
# Keeps eval_input_config only for backwards compatibility. All clients should
# read eval_input_configs instead.
if configs["eval_input_configs"]:
configs["eval_input_config"] = configs["eval_input_configs"][0]
if pipeline_config.HasField("graph_rewriter"):
configs["graph_rewriter_config"] = pipeline_config.graph_rewriter
return configs
def get_graph_rewriter_config_from_file(graph_rewriter_config_file):
"""Parses config for graph rewriter.
Args:
graph_rewriter_config_file: file path to the graph rewriter config.
Returns:
graph_rewriter_pb2.GraphRewriter proto
"""
graph_rewriter_config = graph_rewriter_pb2.GraphRewriter()
with tf.gfile.GFile(graph_rewriter_config_file, "r") as f:
text_format.Merge(f.read(), graph_rewriter_config)
return graph_rewriter_config
def create_pipeline_proto_from_configs(configs):
"""Creates a pipeline_pb2.TrainEvalPipelineConfig from configs dictionary.
This function performs the inverse operation of
create_configs_from_pipeline_proto().
Args:
configs: Dictionary of configs. See get_configs_from_pipeline_file().
Returns:
A fully populated pipeline_pb2.TrainEvalPipelineConfig.
"""
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
pipeline_config.model.CopyFrom(configs["model"])
pipeline_config.train_config.CopyFrom(configs["train_config"])
pipeline_config.train_input_reader.CopyFrom(configs["train_input_config"])
pipeline_config.eval_config.CopyFrom(configs["eval_config"])
pipeline_config.eval_input_reader.extend(configs["eval_input_configs"])
if "graph_rewriter_config" in configs:
pipeline_config.graph_rewriter.CopyFrom(configs["graph_rewriter_config"])
return pipeline_config
def save_pipeline_config(pipeline_config, directory):
"""Saves a pipeline config text file to disk.
Args:
pipeline_config: A pipeline_pb2.TrainEvalPipelineConfig.
directory: The model directory into which the pipeline config file will be
saved.
"""
if not file_io.file_exists(directory):
file_io.recursive_create_dir(directory)
pipeline_config_path = os.path.join(directory, "pipeline.config")
config_text = text_format.MessageToString(pipeline_config)
with tf.gfile.Open(pipeline_config_path, "wb") as f:
tf.logging.info("Writing pipeline config file to %s",
pipeline_config_path)
f.write(config_text)
def get_configs_from_multiple_files(model_config_path="",
train_config_path="",
train_input_config_path="",
eval_config_path="",
eval_input_config_path="",
graph_rewriter_config_path=""):
"""Reads training configuration from multiple config files.
Args:
model_config_path: Path to model_pb2.DetectionModel.
train_config_path: Path to train_pb2.TrainConfig.
train_input_config_path: Path to input_reader_pb2.InputReader.
eval_config_path: Path to eval_pb2.EvalConfig.
eval_input_config_path: Path to input_reader_pb2.InputReader.
graph_rewriter_config_path: Path to graph_rewriter_pb2.GraphRewriter.
Returns:
Dictionary of configuration objects. Keys are `model`, `train_config`,
`train_input_config`, `eval_config`, `eval_input_config`. Key/Values are
returned only for valid (non-empty) strings.
"""
configs = {}
if model_config_path:
model_config = model_pb2.DetectionModel()
with tf.gfile.GFile(model_config_path, "r") as f:
text_format.Merge(f.read(), model_config)
configs["model"] = model_config
if train_config_path:
train_config = train_pb2.TrainConfig()
with tf.gfile.GFile(train_config_path, "r") as f:
text_format.Merge(f.read(), train_config)
configs["train_config"] = train_config
if train_input_config_path:
train_input_config = input_reader_pb2.InputReader()
with tf.gfile.GFile(train_input_config_path, "r") as f:
text_format.Merge(f.read(), train_input_config)
configs["train_input_config"] = train_input_config
if eval_config_path:
eval_config = eval_pb2.EvalConfig()
with tf.gfile.GFile(eval_config_path, "r") as f:
text_format.Merge(f.read(), eval_config)
configs["eval_config"] = eval_config
if eval_input_config_path:
eval_input_config = input_reader_pb2.InputReader()
with tf.gfile.GFile(eval_input_config_path, "r") as f:
text_format.Merge(f.read(), eval_input_config)
configs["eval_input_configs"] = [eval_input_config]
if graph_rewriter_config_path:
configs["graph_rewriter_config"] = get_graph_rewriter_config_from_file(
graph_rewriter_config_path)
return configs
def get_number_of_classes(model_config):
"""Returns the number of classes for a detection model.
Args:
model_config: A model_pb2.DetectionModel.
Returns:
Number of classes.
Raises:
ValueError: If the model type is not recognized.
"""
meta_architecture = model_config.WhichOneof("model")
if meta_architecture == "faster_rcnn":
return model_config.faster_rcnn.num_classes
if meta_architecture == "ssd":
return model_config.ssd.num_classes
raise ValueError("Expected the model to be one of 'faster_rcnn' or 'ssd'.")
def get_optimizer_type(train_config):
"""Returns the optimizer type for training.
Args:
train_config: A train_pb2.TrainConfig.
Returns:
The type of the optimizer
"""
return train_config.optimizer.WhichOneof("optimizer")
def get_learning_rate_type(optimizer_config):
"""Returns the learning rate type for training.
Args:
optimizer_config: An optimizer_pb2.Optimizer.
Returns:
The type of the learning rate.
"""
return optimizer_config.learning_rate.WhichOneof("learning_rate")
def _is_generic_key(key):
"""Determines whether the key starts with a generic config dictionary key."""
for prefix in [
"graph_rewriter_config",
"model",
"train_input_config",
"train_config",
"eval_config"]:
if key.startswith(prefix + "."):
return True
return False
def _check_and_convert_legacy_input_config_key(key):
"""Checks key and converts legacy input config update to specific update.
Args:
key: string indicates the target of update operation.
Returns:
is_valid_input_config_key: A boolean indicating whether the input key is to
update input config(s).
key_name: 'eval_input_configs' or 'train_input_config' string if
is_valid_input_config_key is true. None if is_valid_input_config_key is
false.
input_name: always returns None since legacy input config key never
specifies the target input config. Keeping this output only to match the
output form defined for input config update.
field_name: the field name in input config. `key` itself if
is_valid_input_config_key is false.
"""
key_name = None
input_name = None
field_name = key
is_valid_input_config_key = True
if field_name == "train_shuffle":
key_name = "train_input_config"
field_name = "shuffle"
elif field_name == "eval_shuffle":
key_name = "eval_input_configs"
field_name = "shuffle"
elif field_name == "train_input_path":
key_name = "train_input_config"
field_name = "input_path"
elif field_name == "eval_input_path":
key_name = "eval_input_configs"
field_name = "input_path"
elif field_name == "append_train_input_path":
key_name = "train_input_config"
field_name = "input_path"
elif field_name == "append_eval_input_path":
key_name = "eval_input_configs"
field_name = "input_path"
else:
is_valid_input_config_key = False
return is_valid_input_config_key, key_name, input_name, field_name
def check_and_parse_input_config_key(configs, key):
"""Checks key and returns specific fields if key is valid input config update.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
key: string indicates the target of update operation.
Returns:
is_valid_input_config_key: A boolean indicate whether the input key is to
update input config(s).
key_name: 'eval_input_configs' or 'train_input_config' string if
is_valid_input_config_key is true. None if is_valid_input_config_key is
false.
input_name: the name of the input config to be updated. None if
is_valid_input_config_key is false.
field_name: the field name in input config. `key` itself if
is_valid_input_config_key is false.
Raises:
ValueError: when the input key format doesn't match any known formats.
ValueError: if key_name doesn't match 'eval_input_configs' or
'train_input_config'.
ValueError: if input_name doesn't match any name in train or eval input
configs.
ValueError: if field_name doesn't match any supported fields.
"""
key_name = None
input_name = None
field_name = None
fields = key.split(":")
if len(fields) == 1:
field_name = key
return _check_and_convert_legacy_input_config_key(key)
elif len(fields) == 3:
key_name = fields[0]
input_name = fields[1]
field_name = fields[2]
else:
raise ValueError("Invalid key format when overriding configs.")
# Checks if key_name is valid for specific update.
if key_name not in ["eval_input_configs", "train_input_config"]:
raise ValueError("Invalid key_name when overriding input config.")
# Checks if input_name is valid for specific update. For train input config it
# should match configs[key_name].name, for eval input configs it should match
# the name field of one of the eval_input_configs.
if isinstance(configs[key_name], input_reader_pb2.InputReader):
is_valid_input_name = configs[key_name].name == input_name
else:
is_valid_input_name = input_name in [
eval_input_config.name for eval_input_config in configs[key_name]
]
if not is_valid_input_name:
raise ValueError("Invalid input_name when overriding input config.")
# Checks if field_name is valid for specific update.
if field_name not in [
"input_path", "label_map_path", "shuffle", "mask_type",
"sample_1_of_n_examples"
]:
raise ValueError("Invalid field_name when overriding input config.")
return True, key_name, input_name, field_name
def merge_external_params_with_configs(configs, hparams=None, kwargs_dict=None):
"""Updates `configs` dictionary based on supplied parameters.
This utility is for modifying specific fields in the object detection configs.
Say that one would like to experiment with different learning rates, momentum
values, or batch sizes. Rather than creating a new config text file for each
experiment, one can use a single base config file, and update particular
values.
There are two types of field overrides:
1. Strategy-based overrides, which update multiple relevant configuration
options. For example, updating `learning_rate` will update both the warmup and
final learning rates.
In this case key can be one of the following formats:
1. legacy update: single string that indicates the attribute to be
updated. E.g. 'label_map_path', 'eval_input_path', 'shuffle'.
Note that when updating fields (e.g. eval_input_path, eval_shuffle) in
eval_input_configs, the override will only be applied when
eval_input_configs has exactly 1 element.
2. specific update: colon separated string that indicates which field in
which input_config to update. It should have 3 fields:
- key_name: Name of the input config we should update, either
'train_input_config' or 'eval_input_configs'
- input_name: a 'name' that can be used to identify elements, especially
when configs[key_name] is a repeated field.
- field_name: name of the field that you want to override.
For example, given configs dict as below:
configs = {
'model': {...}
'train_config': {...}
'train_input_config': {...}
'eval_config': {...}
'eval_input_configs': [{ name:"eval_coco", ...},
{ name:"eval_voc", ... }]
}
Assume we want to update the input_path of the eval_input_config
whose name is 'eval_coco'. The `key` would then be:
'eval_input_configs:eval_coco:input_path'
2. Generic key/value, which update a specific parameter based on namespaced
configuration keys. For example,
`model.ssd.loss.hard_example_miner.max_negatives_per_positive` will update the
hard example miner configuration for an SSD model config. Generic overrides
are automatically detected based on the namespaced keys.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
hparams: A `HParams`.
kwargs_dict: Extra keyword arguments that are treated the same way as
attribute/value pairs in `hparams`. Note that hyperparameters with the
same names will override keyword arguments.
Returns:
`configs` dictionary.
Raises:
ValueError: when the key string doesn't match any of its allowed formats.
"""
if kwargs_dict is None:
kwargs_dict = {}
if hparams:
kwargs_dict.update(hparams.values())
for key, value in kwargs_dict.items():
tf.logging.info("Maybe overwriting %s: %s", key, value)
# pylint: disable=g-explicit-bool-comparison
if value == "" or value is None:
continue
# pylint: enable=g-explicit-bool-comparison
elif _maybe_update_config_with_key_value(configs, key, value):
continue
elif _is_generic_key(key):
_update_generic(configs, key, value)
else:
tf.logging.info("Ignoring config override key: %s", key)
return configs
def _maybe_update_config_with_key_value(configs, key, value):
"""Checks key type and updates `configs` with the key value pair accordingly.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
key: String indicates the field(s) to be updated.
value: Value used to override existing field value.
Returns:
A boolean value that indicates whether the override succeeds.
Raises:
ValueError: when the key string doesn't match any of the formats above.
"""
is_valid_input_config_key, key_name, input_name, field_name = (
check_and_parse_input_config_key(configs, key))
if is_valid_input_config_key:
update_input_reader_config(
configs,
key_name=key_name,
input_name=input_name,
field_name=field_name,
value=value)
elif field_name == "learning_rate":
_update_initial_learning_rate(configs, value)
elif field_name == "batch_size":
_update_batch_size(configs, value)
elif field_name == "momentum_optimizer_value":
_update_momentum_optimizer_value(configs, value)
elif field_name == "classification_localization_weight_ratio":
# Localization weight is fixed to 1.0.
_update_classification_localization_weight_ratio(configs, value)
elif field_name == "focal_loss_gamma":
_update_focal_loss_gamma(configs, value)
elif field_name == "focal_loss_alpha":
_update_focal_loss_alpha(configs, value)
elif field_name == "train_steps":
_update_train_steps(configs, value)
elif field_name == "label_map_path":
_update_label_map_path(configs, value)
elif field_name == "mask_type":
_update_mask_type(configs, value)
elif field_name == "sample_1_of_n_eval_examples":
_update_all_eval_input_configs(configs, "sample_1_of_n_examples", value)
elif field_name == "eval_num_epochs":
_update_all_eval_input_configs(configs, "num_epochs", value)
elif field_name == "eval_with_moving_averages":
_update_use_moving_averages(configs, value)
elif field_name == "retain_original_images_in_eval":
_update_retain_original_images(configs["eval_config"], value)
elif field_name == "use_bfloat16":
_update_use_bfloat16(configs, value)
else:
return False
return True
def _update_tf_record_input_path(input_config, input_path):
"""Updates input configuration to reflect a new input path.
The input_config object is updated in place, and hence not returned.
Args:
input_config: A input_reader_pb2.InputReader.
input_path: A path to data or list of paths.
Raises:
TypeError: if input reader type is not `tf_record_input_reader`.
"""
input_reader_type = input_config.WhichOneof("input_reader")
if input_reader_type == "tf_record_input_reader":
input_config.tf_record_input_reader.ClearField("input_path")
if isinstance(input_path, list):
input_config.tf_record_input_reader.input_path.extend(input_path)
else:
input_config.tf_record_input_reader.input_path.append(input_path)
else:
raise TypeError("Input reader type must be `tf_record_input_reader`.")
def update_input_reader_config(configs,
key_name=None,
input_name=None,
field_name=None,
value=None,
path_updater=_update_tf_record_input_path):
"""Updates specified input reader config field.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
key_name: Name of the input config we should update, either
'train_input_config' or 'eval_input_configs'
input_name: String name used to identify input config to update with. Should
be either None or value of the 'name' field in one of the input reader
configs.
field_name: Field name in input_reader_pb2.InputReader.
value: Value used to override existing field value.
path_updater: helper function used to update the input path. Only used when
field_name is "input_path".
Raises:
ValueError: when input field_name is None.
ValueError: when input_name is None and number of eval_input_readers does
not equal to 1.
"""
if isinstance(configs[key_name], input_reader_pb2.InputReader):
# Updates singular input_config object.
target_input_config = configs[key_name]
if field_name == "input_path":
path_updater(input_config=target_input_config, input_path=value)
else:
setattr(target_input_config, field_name, value)
elif input_name is None and len(configs[key_name]) == 1:
# Updates first (and the only) object of input_config list.
target_input_config = configs[key_name][0]
if field_name == "input_path":
path_updater(input_config=target_input_config, input_path=value)
else:
setattr(target_input_config, field_name, value)
elif input_name is not None and len(configs[key_name]):
# Updates input_config whose name matches input_name.
update_count = 0
for input_config in configs[key_name]:
if input_config.name == input_name:
setattr(input_config, field_name, value)
update_count = update_count + 1
if not update_count:
raise ValueError(
"Input name {} not found when overriding.".format(input_name))
elif update_count > 1:
raise ValueError("Duplicate input name found when overriding.")
else:
key_name = "None" if key_name is None else key_name
input_name = "None" if input_name is None else input_name
field_name = "None" if field_name is None else field_name
raise ValueError("Unknown input config overriding: "
"key_name:{}, input_name:{}, field_name:{}.".format(
key_name, input_name, field_name))
def _update_initial_learning_rate(configs, learning_rate):
"""Updates `configs` to reflect the new initial learning rate.
This function updates the initial learning rate. For learning rate schedules,
all other defined learning rates in the pipeline config are scaled to maintain
their same ratio with the initial learning rate.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
learning_rate: Initial learning rate for optimizer.
Raises:
TypeError: if optimizer type is not supported, or if learning rate type is
not supported.
"""
optimizer_type = get_optimizer_type(configs["train_config"])
if optimizer_type == "rms_prop_optimizer":
optimizer_config = configs["train_config"].optimizer.rms_prop_optimizer
elif optimizer_type == "momentum_optimizer":
optimizer_config = configs["train_config"].optimizer.momentum_optimizer
elif optimizer_type == "adam_optimizer":
optimizer_config = configs["train_config"].optimizer.adam_optimizer
else:
raise TypeError("Optimizer %s is not supported." % optimizer_type)
learning_rate_type = get_learning_rate_type(optimizer_config)
if learning_rate_type == "constant_learning_rate":
constant_lr = optimizer_config.learning_rate.constant_learning_rate
constant_lr.learning_rate = learning_rate
elif learning_rate_type == "exponential_decay_learning_rate":
exponential_lr = (
optimizer_config.learning_rate.exponential_decay_learning_rate)
exponential_lr.initial_learning_rate = learning_rate
elif learning_rate_type == "manual_step_learning_rate":
manual_lr = optimizer_config.learning_rate.manual_step_learning_rate
original_learning_rate = manual_lr.initial_learning_rate
learning_rate_scaling = float(learning_rate) / original_learning_rate
manual_lr.initial_learning_rate = learning_rate
for schedule in manual_lr.schedule:
schedule.learning_rate *= learning_rate_scaling
elif learning_rate_type == "cosine_decay_learning_rate":
cosine_lr = optimizer_config.learning_rate.cosine_decay_learning_rate
learning_rate_base = cosine_lr.learning_rate_base
warmup_learning_rate = cosine_lr.warmup_learning_rate
warmup_scale_factor = warmup_learning_rate / learning_rate_base
cosine_lr.learning_rate_base = learning_rate
cosine_lr.warmup_learning_rate = warmup_scale_factor * learning_rate
else:
raise TypeError("Learning rate %s is not supported." % learning_rate_type)
def _update_batch_size(configs, batch_size):
"""Updates `configs` to reflect the new training batch size.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
batch_size: Batch size to use for training (Ideally a power of 2). Inputs
are rounded, and capped to be 1 or greater.
"""
configs["train_config"].batch_size = max(1, int(round(batch_size)))
def _validate_message_has_field(message, field):
if not message.HasField(field):
raise ValueError("Expecting message to have field %s" % field)
def _update_generic(configs, key, value):
"""Update a pipeline configuration parameter based on a generic key/value.
Args:
configs: Dictionary of pipeline configuration protos.
key: A string key, dot-delimited to represent the argument key.
e.g. "model.ssd.train_config.batch_size"
value: A value to set the argument to. The type of the value must match the
type for the protocol buffer. Note that setting the wrong type will
result in a TypeError.
e.g. 42
Raises:
ValueError if the message key does not match the existing proto fields.
TypeError the value type doesn't match the protobuf field type.
"""
fields = key.split(".")
first_field = fields.pop(0)
last_field = fields.pop()
message = configs[first_field]
for field in fields:
_validate_message_has_field(message, field)
message = getattr(message, field)
_validate_message_has_field(message, last_field)
setattr(message, last_field, value)
def _update_momentum_optimizer_value(configs, momentum):
"""Updates `configs` to reflect the new momentum value.
Momentum is only supported for RMSPropOptimizer and MomentumOptimizer. For any
other optimizer, no changes take place. The configs dictionary is updated in
place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
momentum: New momentum value. Values are clipped at 0.0 and 1.0.
Raises:
TypeError: If the optimizer type is not `rms_prop_optimizer` or
`momentum_optimizer`.
"""
optimizer_type = get_optimizer_type(configs["train_config"])
if optimizer_type == "rms_prop_optimizer":
optimizer_config = configs["train_config"].optimizer.rms_prop_optimizer
elif optimizer_type == "momentum_optimizer":
optimizer_config = configs["train_config"].optimizer.momentum_optimizer
else:
raise TypeError("Optimizer type must be one of `rms_prop_optimizer` or "
"`momentum_optimizer`.")
optimizer_config.momentum_optimizer_value = min(max(0.0, momentum), 1.0)
def _update_classification_localization_weight_ratio(configs, ratio):
"""Updates the classification/localization weight loss ratio.
Detection models usually define a loss weight for both classification and
objectness. This function updates the weights such that the ratio between
classification weight to localization weight is the ratio provided.
Arbitrarily, localization weight is set to 1.0.
Note that in the case of Faster R-CNN, this same ratio is applied to the first
stage objectness loss weight relative to localization loss weight.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
ratio: Desired ratio of classification (and/or objectness) loss weight to
localization loss weight.
"""
meta_architecture = configs["model"].WhichOneof("model")
if meta_architecture == "faster_rcnn":
model = configs["model"].faster_rcnn
model.first_stage_localization_loss_weight = 1.0
model.first_stage_objectness_loss_weight = ratio
model.second_stage_localization_loss_weight = 1.0
model.second_stage_classification_loss_weight = ratio
if meta_architecture == "ssd":
model = configs["model"].ssd
model.loss.localization_weight = 1.0
model.loss.classification_weight = ratio
def _get_classification_loss(model_config):
"""Returns the classification loss for a model."""
meta_architecture = model_config.WhichOneof("model")
if meta_architecture == "faster_rcnn":
model = model_config.faster_rcnn
classification_loss = model.second_stage_classification_loss
elif meta_architecture == "ssd":
model = model_config.ssd
classification_loss = model.loss.classification_loss
else:
raise TypeError("Did not recognize the model architecture.")
return classification_loss
def _update_focal_loss_gamma(configs, gamma):
"""Updates the gamma value for a sigmoid focal loss.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
gamma: Exponent term in focal loss.
Raises:
TypeError: If the classification loss is not `weighted_sigmoid_focal`.
"""
classification_loss = _get_classification_loss(configs["model"])
classification_loss_type = classification_loss.WhichOneof(
"classification_loss")
if classification_loss_type != "weighted_sigmoid_focal":
raise TypeError("Classification loss must be `weighted_sigmoid_focal`.")
classification_loss.weighted_sigmoid_focal.gamma = gamma
def _update_focal_loss_alpha(configs, alpha):
"""Updates the alpha value for a sigmoid focal loss.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
alpha: Class weight multiplier for sigmoid loss.
Raises:
TypeError: If the classification loss is not `weighted_sigmoid_focal`.
"""
classification_loss = _get_classification_loss(configs["model"])
classification_loss_type = classification_loss.WhichOneof(
"classification_loss")
if classification_loss_type != "weighted_sigmoid_focal":
raise TypeError("Classification loss must be `weighted_sigmoid_focal`.")
classification_loss.weighted_sigmoid_focal.alpha = alpha
def _update_train_steps(configs, train_steps):
"""Updates `configs` to reflect new number of training steps."""
configs["train_config"].num_steps = int(train_steps)
def _update_eval_steps(configs, eval_steps):
"""Updates `configs` to reflect new number of eval steps per evaluation."""
configs["eval_config"].num_examples = int(eval_steps)
def _update_all_eval_input_configs(configs, field, value):
"""Updates the content of `field` with `value` for all eval input configs."""
for eval_input_config in configs["eval_input_configs"]:
setattr(eval_input_config, field, value)
def _update_label_map_path(configs, label_map_path):
"""Updates the label map path for both train and eval input readers.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
label_map_path: New path to `StringIntLabelMap` pbtxt file.
"""
configs["train_input_config"].label_map_path = label_map_path
_update_all_eval_input_configs(configs, "label_map_path", label_map_path)
def _update_mask_type(configs, mask_type):
"""Updates the mask type for both train and eval input readers.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
mask_type: A string name representing a value of
input_reader_pb2.InstanceMaskType
"""
configs["train_input_config"].mask_type = mask_type
_update_all_eval_input_configs(configs, "mask_type", mask_type)
def _update_use_moving_averages(configs, use_moving_averages):
"""Updates the eval config option to use or not use moving averages.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
use_moving_averages: Boolean indicating whether moving average variables
should be loaded during evaluation.
"""
configs["eval_config"].use_moving_averages = use_moving_averages
def _update_retain_original_images(eval_config, retain_original_images):
"""Updates eval config with option to retain original images.
The eval_config object is updated in place, and hence not returned.
Args:
eval_config: A eval_pb2.EvalConfig.
retain_original_images: Boolean indicating whether to retain original images
in eval mode.
"""
eval_config.retain_original_images = retain_original_images
def _update_use_bfloat16(configs, use_bfloat16):
"""Updates `configs` to reflect the new setup on whether to use bfloat16.
The configs dictionary is updated in place, and hence not returned.
Args:
configs: Dictionary of configuration objects. See outputs from
get_configs_from_pipeline_file() or get_configs_from_multiple_files().
use_bfloat16: A bool, indicating whether to use bfloat16 for training.
"""
configs["train_config"].use_bfloat16 = use_bfloat16
|