INSTRUCTION
stringlengths 1
8.43k
| RESPONSE
stringlengths 75
104k
|
|---|---|
Returns json compatible state of the Button instance.
|
def json(self) -> dict:
"""Returns json compatible state of the Button instance.
Returns:
control_json: Json representation of Button state.
"""
content = {}
content['name'] = self.name
content['callback'] = self.callback
self.control_json['content'] = content
return self.control_json
|
Returns MS Bot Framework compatible state of the Button instance.
|
def ms_bot_framework(self) -> dict:
"""Returns MS Bot Framework compatible state of the Button instance.
Creates MS Bot Framework CardAction (button) with postBack value return.
Returns:
control_json: MS Bot Framework representation of Button state.
"""
card_action = {}
card_action['type'] = 'postBack'
card_action['title'] = self.name
card_action['value'] = self.callback = self.callback
return card_action
|
Returns json compatible state of the ButtonsFrame instance.
|
def json(self) -> dict:
"""Returns json compatible state of the ButtonsFrame instance.
Returns json compatible state of the ButtonsFrame instance including
all nested buttons.
Returns:
control_json: Json representation of ButtonsFrame state.
"""
content = {}
if self.text:
content['text'] = self.text
content['controls'] = [control.json() for control in self.content]
self.control_json['content'] = content
return self.control_json
|
Returns MS Bot Framework compatible state of the ButtonsFrame instance.
|
def ms_bot_framework(self) -> dict:
"""Returns MS Bot Framework compatible state of the ButtonsFrame instance.
Creating MS Bot Framework activity blank with RichCard in "attachments". RichCard
is populated with CardActions corresponding buttons embedded in ButtonsFrame.
Returns:
control_json: MS Bot Framework representation of ButtonsFrame state.
"""
rich_card = {}
buttons = [button.ms_bot_framework() for button in self.content]
rich_card['buttons'] = buttons
if self.text:
rich_card['title'] = self.text
attachments = [
{
"contentType": "application/vnd.microsoft.card.thumbnail",
"content": rich_card
}
]
out_activity = {}
out_activity['type'] = 'message'
out_activity['attachments'] = attachments
return out_activity
|
Calculates Exact Match score between y_true and y_predicted EM score uses the best matching y_true answer: if y_pred equal at least to one answer in y_true then EM = 1 else EM = 0
|
def squad_v2_exact_match(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
The same as in SQuAD-v2.0
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: list of predicted answers
Returns:
exact match score : float
"""
EM_total = sum(normalize_answer(prediction) in map(normalize_answer, ground_truth)
for ground_truth, prediction in zip(y_true, y_predicted))
return 100 * EM_total / len(y_true) if len(y_true) > 0 else 0
|
Calculates Exact Match score between y_true and y_predicted EM score uses the best matching y_true answer: if y_pred equal at least to one answer in y_true then EM = 1 else EM = 0 Skips examples without an answer. Args: y_true: list of correct answers ( correct answers are represented by list of strings ) y_predicted: list of predicted answers Returns: exact match score: float
|
def squad_v1_exact_match(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates Exact Match score between y_true and y_predicted
EM score uses the best matching y_true answer:
if y_pred equal at least to one answer in y_true then EM = 1, else EM = 0
Skips examples without an answer.
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: list of predicted answers
Returns:
exact match score : float
"""
EM_total = 0
count = 0
for ground_truth, prediction in zip(y_true, y_predicted):
if len(ground_truth[0]) == 0:
# skip empty answers
continue
count += 1
EMs = [int(normalize_answer(gt) == normalize_answer(prediction)) for gt in ground_truth]
EM_total += max(EMs)
return 100 * EM_total / count if count > 0 else 0
|
Calculates F - 1 score between y_true and y_predicted F - 1 score uses the best matching y_true answer
|
def squad_v2_f1(y_true: List[List[str]], y_predicted: List[str]) -> float:
""" Calculates F-1 score between y_true and y_predicted
F-1 score uses the best matching y_true answer
The same as in SQuAD-v2.0
Args:
y_true: list of correct answers (correct answers are represented by list of strings)
y_predicted: list of predicted answers
Returns:
F-1 score : float
"""
f1_total = 0.0
for ground_truth, prediction in zip(y_true, y_predicted):
prediction_tokens = normalize_answer(prediction).split()
f1s = []
for gt in ground_truth:
gt_tokens = normalize_answer(gt).split()
if len(gt_tokens) == 0 or len(prediction_tokens) == 0:
f1s.append(float(gt_tokens == prediction_tokens))
continue
common = Counter(prediction_tokens) & Counter(gt_tokens)
num_same = sum(common.values())
if num_same == 0:
f1s.append(0.0)
continue
precision = 1.0 * num_same / len(prediction_tokens)
recall = 1.0 * num_same / len(gt_tokens)
f1 = (2 * precision * recall) / (precision + recall)
f1s.append(f1)
f1_total += max(f1s)
return 100 * f1_total / len(y_true) if len(y_true) > 0 else 0
|
Calculates recall at k ranking metric.
|
def recall_at_k(y_true: List[int], y_pred: List[List[np.ndarray]], k: int):
"""
Calculates recall at k ranking metric.
Args:
y_true: Labels. Not used in the calculation of the metric.
y_predicted: Predictions.
Each prediction contains ranking score of all ranking candidates for the particular data sample.
It is supposed that the ranking score for the true candidate goes first in the prediction.
Returns:
Recall at k
"""
num_examples = float(len(y_pred))
predictions = np.array(y_pred)
predictions = np.flip(np.argsort(predictions, -1), -1)[:, :k]
num_correct = 0
for el in predictions:
if 0 in el:
num_correct += 1
return float(num_correct) / num_examples
|
r Return True if at least one GPU is available
|
def check_gpu_existence():
r"""Return True if at least one GPU is available"""
global _gpu_available
if _gpu_available is None:
sess_config = tf.ConfigProto()
sess_config.gpu_options.allow_growth = True
try:
with tf.Session(config=sess_config):
device_list = device_lib.list_local_devices()
_gpu_available = any(device.device_type == 'GPU' for device in device_list)
except AttributeError as e:
log.warning(f'Got an AttributeError `{e}`, assuming documentation building')
_gpu_available = False
return _gpu_available
|
Recursively apply config s variables values to its property
|
def _parse_config_property(item: _T, variables: Dict[str, Union[str, Path, float, bool, None]]) -> _T:
"""Recursively apply config's variables values to its property"""
if isinstance(item, str):
return item.format(**variables)
elif isinstance(item, list):
return [_parse_config_property(item, variables) for item in item]
elif isinstance(item, dict):
return {k: _parse_config_property(v, variables) for k, v in item.items()}
else:
return item
|
Read config s variables and apply their values to all its properties
|
def parse_config(config: Union[str, Path, dict]) -> dict:
"""Read config's variables and apply their values to all its properties"""
if isinstance(config, (str, Path)):
config = read_json(find_config(config))
variables = {
'DEEPPAVLOV_PATH': os.getenv(f'DP_DEEPPAVLOV_PATH', Path(__file__).parent.parent.parent)
}
for name, value in config.get('metadata', {}).get('variables', {}).items():
env_name = f'DP_{name}'
if env_name in os.environ:
value = os.getenv(env_name)
variables[name] = value.format(**variables)
return _parse_config_property(config, variables)
|
Convert relative paths to absolute with resolving user directory.
|
def expand_path(path: Union[str, Path]) -> Path:
"""Convert relative paths to absolute with resolving user directory."""
return Path(path).expanduser().resolve()
|
Builds and returns the Component from corresponding dictionary of parameters.
|
def from_params(params: Dict, mode: str = 'infer', serialized: Any = None, **kwargs) -> Component:
"""Builds and returns the Component from corresponding dictionary of parameters."""
# what is passed in json:
config_params = {k: _resolve(v) for k, v in params.items()}
# get component by reference (if any)
if 'ref' in config_params:
try:
component = _refs[config_params['ref']]
if serialized is not None:
component.deserialize(serialized)
return component
except KeyError:
e = ConfigError('Component with id "{id}" was referenced but not initialized'
.format(id=config_params['ref']))
log.exception(e)
raise e
elif 'config_path' in config_params:
from deeppavlov.core.commands.infer import build_model
refs = _refs.copy()
_refs.clear()
config = parse_config(expand_path(config_params['config_path']))
model = build_model(config, serialized=serialized)
_refs.clear()
_refs.update(refs)
try:
_refs[config_params['id']] = model
except KeyError:
pass
return model
cls_name = config_params.pop('class_name', None)
if not cls_name:
e = ConfigError('Component config has no `class_name` nor `ref` fields')
log.exception(e)
raise e
cls = get_model(cls_name)
# find the submodels params recursively
config_params = {k: _init_param(v, mode) for k, v in config_params.items()}
try:
spec = inspect.getfullargspec(cls)
if 'mode' in spec.args+spec.kwonlyargs or spec.varkw is not None:
kwargs['mode'] = mode
component = cls(**dict(config_params, **kwargs))
try:
_refs[config_params['id']] = component
except KeyError:
pass
except Exception:
log.exception("Exception in {}".format(cls))
raise
if serialized is not None:
component.deserialize(serialized)
return component
|
Thread run method implementation.
|
def run(self) -> None:
"""Thread run method implementation."""
while True:
request = self.input_queue.get()
response = self._handle_request(request)
self.output_queue.put(response)
|
Deletes Conversation instance.
|
def _del_conversation(self, conversation_key: str) -> None:
"""Deletes Conversation instance.
Args:
conversation_key: Conversation key.
"""
if conversation_key in self.conversations.keys():
del self.conversations[conversation_key]
log.info(f'Deleted conversation, key: {conversation_key}')
|
Conducts cleanup of periodical certificates with expired validation.
|
def _refresh_valid_certs(self) -> None:
"""Conducts cleanup of periodical certificates with expired validation."""
self.timer = Timer(REFRESH_VALID_CERTS_PERIOD_SECS, self._refresh_valid_certs)
self.timer.start()
expired_certificates = []
for valid_cert_url, valid_cert in self.valid_certificates.items():
valid_cert: ValidatedCert = valid_cert
cert_expiration_time: datetime = valid_cert.expiration_timestamp
if datetime.utcnow() > cert_expiration_time:
expired_certificates.append(valid_cert_url)
for expired_cert_url in expired_certificates:
del self.valid_certificates[expired_cert_url]
log.info(f'Validation period of {expired_cert_url} certificate expired')
|
Conducts series of Alexa request verifications against Amazon Alexa requirements.
|
def _verify_request(self, signature_chain_url: str, signature: str, request_body: bytes) -> bool:
"""Conducts series of Alexa request verifications against Amazon Alexa requirements.
Args:
signature_chain_url: Signature certificate URL from SignatureCertChainUrl HTTP header.
signature: Base64 decoded Alexa request signature from Signature HTTP header.
request_body: full HTTPS request body
Returns:
result: True if verification was successful, False if not.
"""
if signature_chain_url not in self.valid_certificates.keys():
amazon_cert: X509 = verify_cert(signature_chain_url)
if amazon_cert:
amazon_cert_lifetime: timedelta = self.config['amazon_cert_lifetime']
expiration_timestamp = datetime.utcnow() + amazon_cert_lifetime
validated_cert = ValidatedCert(cert=amazon_cert, expiration_timestamp=expiration_timestamp)
self.valid_certificates[signature_chain_url] = validated_cert
log.info(f'Certificate {signature_chain_url} validated')
else:
log.error(f'Certificate {signature_chain_url} validation failed')
return False
else:
validated_cert: ValidatedCert = self.valid_certificates[signature_chain_url]
amazon_cert: X509 = validated_cert.cert
if verify_signature(amazon_cert, signature, request_body):
result = True
else:
log.error(f'Failed signature verification for request: {request_body.decode("utf-8", "replace")}')
result = False
return result
|
Processes Alexa requests from skill server and returns responses to Alexa.
|
def _handle_request(self, request: dict) -> dict:
"""Processes Alexa requests from skill server and returns responses to Alexa.
Args:
request: Dict with Alexa request payload and metadata.
Returns:
result: Alexa formatted or error response.
"""
request_body: bytes = request['request_body']
signature_chain_url: str = request['signature_chain_url']
signature: str = request['signature']
alexa_request: dict = request['alexa_request']
if not self._verify_request(signature_chain_url, signature, request_body):
return {'error': 'failed certificate/signature check'}
timestamp_str = alexa_request['request']['timestamp']
timestamp_datetime = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%SZ')
now = datetime.utcnow()
delta = now - timestamp_datetime if now >= timestamp_datetime else timestamp_datetime - now
if abs(delta.seconds) > REQUEST_TIMESTAMP_TOLERANCE_SECS:
log.error(f'Failed timestamp check for request: {request_body.decode("utf-8", "replace")}')
return {'error': 'failed request timestamp check'}
conversation_key = alexa_request['session']['user']['userId']
if conversation_key not in self.conversations.keys():
if self.config['multi_instance']:
conv_agent = self._init_agent()
log.info('New conversation instance level agent initiated')
else:
conv_agent = self.agent
self.conversations[conversation_key] = \
Conversation(config=self.config,
agent=conv_agent,
conversation_key=conversation_key,
self_destruct_callback=lambda: self._del_conversation(conversation_key))
log.info(f'Created new conversation, key: {conversation_key}')
conversation = self.conversations[conversation_key]
response = conversation.handle_request(alexa_request)
return response
|
It is a implementation of the constrained softmax ( csoftmax ) for slice. Based on the paper: https:// andre - martins. github. io/ docs/ emnlp2017_final. pdf Learning What s Easy: Fully Differentiable Neural Easy - First Taggers ( page 4 ) Args: input: A list of [ input tensor cumulative attention ]. Returns: output: A list of [ csoftmax results masks ]
|
def csoftmax_for_slice(input):
""" It is a implementation of the constrained softmax (csoftmax) for slice.
Based on the paper:
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers" (page 4)
Args:
input: A list of [input tensor, cumulative attention].
Returns:
output: A list of [csoftmax results, masks]
"""
[ten, u] = input
shape_t = ten.shape
shape_u = u.shape
ten -= tf.reduce_mean(ten)
q = tf.exp(ten)
active = tf.ones_like(u, dtype=tf.int32)
mass = tf.constant(0, dtype=tf.float32)
found = tf.constant(True, dtype=tf.bool)
def loop(q_, mask, mass_, found_):
q_list = tf.dynamic_partition(q_, mask, 2)
condition_indices = tf.dynamic_partition(tf.range(tf.shape(q_)[0]), mask, 2) # 0 element it False,
# 1 element if true
p = q_list[1] * (1.0 - mass_) / tf.reduce_sum(q_list[1])
p_new = tf.dynamic_stitch(condition_indices, [q_list[0], p])
# condition verification and mask modification
less_mask = tf.cast(tf.less(u, p_new), tf.int32) # 0 when u is bigger than p, 1 when u is less than p
condition_indices = tf.dynamic_partition(tf.range(tf.shape(p_new)[0]), less_mask,
2) # 0 when u is bigger than p, 1 when u is less than p
split_p_new = tf.dynamic_partition(p_new, less_mask, 2)
split_u = tf.dynamic_partition(u, less_mask, 2)
alpha = tf.dynamic_stitch(condition_indices, [split_p_new[0], split_u[1]])
mass_ += tf.reduce_sum(split_u[1])
mask = mask * (tf.ones_like(less_mask) - less_mask)
found_ = tf.cond(tf.equal(tf.reduce_sum(less_mask), 0),
lambda: False,
lambda: True)
alpha = tf.reshape(alpha, q_.shape)
return alpha, mask, mass_, found_
(csoft, mask_, _, _) = tf.while_loop(cond=lambda _0, _1, _2, f: f,
body=loop,
loop_vars=(q, active, mass, found))
return [csoft, mask_]
|
It is a implementation of the constrained softmax ( csoftmax ). Based on the paper: https:// andre - martins. github. io/ docs/ emnlp2017_final. pdf Learning What s Easy: Fully Differentiable Neural Easy - First Taggers Args: tensor: A tensorflow tensor is score. This tensor have dimensionality [ None n_tokens ] inv_cumulative_att: A inverse cumulative attention tensor with dimensionality [ None n_tokens ] Returns: cs: Tensor at the output with dimensionality [ None n_tokens ]
|
def csoftmax(tensor, inv_cumulative_att):
""" It is a implementation of the constrained softmax (csoftmax).
Based on the paper:
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
tensor: A tensorflow tensor is score. This tensor have dimensionality [None, n_tokens]
inv_cumulative_att: A inverse cumulative attention tensor with dimensionality [None, n_tokens]
Returns:
cs: Tensor at the output with dimensionality [None, n_tokens]
"""
shape_ten = tensor.shape
shape_cum = inv_cumulative_att.shape
merge_tensor = [tensor, inv_cumulative_att]
cs, _ = tf.map_fn(csoftmax_for_slice, merge_tensor, dtype=[tf.float32, tf.float32]) # [bs, L]
return cs
|
It is a implementation one step of block of the Luong et al. attention mechanism with general score and the constrained softmax ( csoftmax ). Based on the papers: https:// arxiv. org/ abs/ 1508. 04025 Effective Approaches to Attention - based Neural Machine Translation https:// andre - martins. github. io/ docs/ emnlp2017_final. pdf Learning What s Easy: Fully Differentiable Neural Easy - First Taggers Args: hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [ None max_num_tokens sketch_hidden_size ] hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [ None max_num_tokens hidden_size_for_attn_alignment ] sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [ None sketch_hidden_size ] key: A tensorflow tensor with dimensionality [ None None key_size ] cum_att: A cumulative attention tensor with dimensionality [ None max_num_tokens ] Returns: next_sketch: Tensor of the current step sketch with dimensionality [ None sketch_hidden_size ] att: Tensor of the current step attention with dimensionality [ None max_num_tokens ] aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [ None hidden_size_for_attn_alignment ]
|
def attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketch, key, cum_att):
""" It is a implementation one step of block of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
sketch: A previous step sketch tensor for a sketch computing. This tensor have dimensionality [None, sketch_hidden_size]
key: A tensorflow tensor with dimensionality [None, None, key_size]
cum_att: A cumulative attention tensor with dimensionality [None, max_num_tokens]
Returns:
next_sketch: Tensor of the current step sketch with dimensionality [None, sketch_hidden_size]
att: Tensor of the current step attention with dimensionality [None, max_num_tokens]
aligned_hidden_sketch: Tensor of aligned hidden state of current step with dimensionality [None, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_step'):
sketch_dims = hidden_for_sketch.get_shape().as_list()
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = hidden_for_attn_alignment.get_shape().as_list()
attn_alignment_hidden_size = attn_alignment_dims[2]
repeated_sketch = tf.tile(tf.reshape(sketch, [-1, 1, hidden_size]), (1,num_tokens, 1))
concat_mem = tf.concat([hidden_for_sketch, repeated_sketch],-1)
concat_mem = tf.reshape(concat_mem, [-1, num_tokens, 2*hidden_size]) # dirty trick
reduce_mem = tf.layers.dense(concat_mem, hidden_size)
projected_key = tf.layers.dense(key, hidden_size)
t_key = tf.reshape(projected_key,[-1, hidden_size, 1])
score = tf.reshape(tf.matmul(reduce_mem, t_key), [-1, num_tokens])
inv_cum_att = tf.reshape(tf.ones_like(cum_att) - cum_att, [-1, num_tokens])
att = csoftmax(score, inv_cum_att)
t_reduce_mem = tf.transpose(reduce_mem, [0,2,1])
t_hidden_for_attn_alignment = tf.transpose(hidden_for_attn_alignment, [0,2,1])
r_att = tf.reshape(att, [-1, num_tokens, 1])
next_sketch = tf.squeeze(tf.matmul(t_reduce_mem,r_att),-1)
aligned_hidden_sketch = tf.squeeze(tf.matmul(t_hidden_for_attn_alignment,r_att),-1)
return next_sketch, att, aligned_hidden_sketch
|
It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax ( csoftmax ). Based on the papers: https:// arxiv. org/ abs/ 1508. 04025 Effective Approaches to Attention - based Neural Machine Translation https:// andre - martins. github. io/ docs/ emnlp2017_final. pdf Learning What s Easy: Fully Differentiable Neural Easy - First Taggers Args: hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [ None max_num_tokens sketch_hidden_size ] hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [ None max_num_tokens hidden_size_for_attn_alignment ] key: A tensorflow tensor with dimensionality [ None None key_size ] attention_depth: Number of usage csoftmax Returns: final_aligned_hiddens: Tensor at the output with dimensionality [ 1 attention_depth hidden_size_for_attn_alignment ]
|
def attention_gen_block(hidden_for_sketch, hidden_for_attn_alignment, key, attention_depth):
""" It is a implementation of the Luong et al. attention mechanism with general score and the constrained softmax (csoftmax).
Based on the papers:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
hidden_for_sketch: A tensorflow tensor for a sketch computing. This tensor have dimensionality [None, max_num_tokens, sketch_hidden_size]
hidden_for_attn_alignment: A tensorflow tensor is aligned for output during a performing. This tensor have dimensionality [None, max_num_tokens, hidden_size_for_attn_alignment]
key: A tensorflow tensor with dimensionality [None, None, key_size]
attention_depth: Number of usage csoftmax
Returns:
final_aligned_hiddens: Tensor at the output with dimensionality [1, attention_depth, hidden_size_for_attn_alignment]
"""
with tf.name_scope('attention_block'):
sketch_dims = tf.shape(hidden_for_sketch)
batch_size = sketch_dims[0]
num_tokens = sketch_dims[1]
hidden_size = sketch_dims[2]
attn_alignment_dims = tf.shape(hidden_for_attn_alignment)
attn_alignment_hidden_size = attn_alignment_dims[2]
sketches = [tf.zeros(shape=[batch_size, hidden_size], dtype=tf.float32)]
aligned_hiddens = []
cum_att = tf.zeros(shape=[batch_size, num_tokens]) # cumulative attention
for i in range(attention_depth):
sketch, cum_att_, aligned_hidden = attention_gen_step(hidden_for_sketch, hidden_for_attn_alignment, sketches[-1], key, cum_att)
sketches.append(sketch) #sketch
aligned_hiddens.append(aligned_hidden) #sketch
cum_att += cum_att_
final_aligned_hiddens = tf.reshape(tf.transpose(tf.stack(aligned_hiddens), [1, 0, 2]),[1, attention_depth, attn_alignment_hidden_size])
return final_aligned_hiddens
|
Returns a class object with the name given as a string.
|
def cls_from_str(name: str) -> type:
"""Returns a class object with the name given as a string."""
try:
module_name, cls_name = name.split(':')
except ValueError:
raise ConfigError('Expected class description in a `module.submodules:ClassName` form, but got `{}`'
.format(name))
return getattr(importlib.import_module(module_name), cls_name)
|
Register classes that could be initialized from JSON configuration file. If name is not passed the class name is converted to snake - case.
|
def register(name: str = None) -> type:
"""
Register classes that could be initialized from JSON configuration file.
If name is not passed, the class name is converted to snake-case.
"""
def decorate(model_cls: type, reg_name: str = None) -> type:
model_name = reg_name or short_name(model_cls)
global _REGISTRY
cls_name = model_cls.__module__ + ':' + model_cls.__name__
if model_name in _REGISTRY and _REGISTRY[model_name] != cls_name:
logger.warning('Registry name "{}" has been already registered and will be overwritten.'.format(model_name))
_REGISTRY[model_name] = cls_name
return model_cls
return lambda model_cls_name: decorate(model_cls_name, name)
|
Returns a registered class object with the name given in the string.
|
def get_model(name: str) -> type:
"""Returns a registered class object with the name given in the string."""
if name not in _REGISTRY:
if ':' not in name:
raise ConfigError("Model {} is not registered.".format(name))
return cls_from_str(name)
return cls_from_str(_REGISTRY[name])
|
It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper: https:// arxiv. org/ abs/ 1508. 04025 Effective Approaches to Attention - based Neural Machine Translation Args: key: A tensorflow tensor with dimensionality [ None None key_size ] context: A tensorflow tensor with dimensionality [ None None max_num_tokens token_size ] hidden_size: Number of units in hidden representation projected_align: Using bidirectional lstm for hidden representation of context. If true beetween input and attention mechanism insert layer of bidirectional lstm with dimensionality [ hidden_size ]. If false bidirectional lstm is not used. Returns: output: Tensor at the output with dimensionality [ None None hidden_size ]
|
def general_attention(key, context, hidden_size, projected_align=False):
""" It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
Args:
key: A tensorflow tensor with dimensionality [None, None, key_size]
context: A tensorflow tensor with dimensionality [None, None, max_num_tokens, token_size]
hidden_size: Number of units in hidden representation
projected_align: Using bidirectional lstm for hidden representation of context.
If true, beetween input and attention mechanism insert layer of bidirectional lstm with dimensionality [hidden_size].
If false, bidirectional lstm is not used.
Returns:
output: Tensor at the output with dimensionality [None, None, hidden_size]
"""
if hidden_size % 2 != 0:
raise ValueError("hidden size must be dividable by two")
batch_size = tf.shape(context)[0]
max_num_tokens, token_size = context.get_shape().as_list()[-2:]
r_context = tf.reshape(context, shape=[-1, max_num_tokens, token_size])
# projected_key: [None, None, hidden_size]
projected_key = \
tf.layers.dense(key, hidden_size, kernel_initializer=xav())
r_projected_key = tf.reshape(projected_key, shape=[-1, hidden_size, 1])
lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(hidden_size//2)
lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(hidden_size//2)
(output_fw, output_bw), states = \
tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell,
cell_bw=lstm_bw_cell,
inputs=r_context,
dtype=tf.float32)
# bilstm_output: [-1, max_num_tokens, hidden_size]
bilstm_output = tf.concat([output_fw, output_bw], -1)
attn = tf.nn.softmax(tf.matmul(bilstm_output, r_projected_key), dim=1)
if projected_align:
log.info("Using projected attention alignment")
t_context = tf.transpose(bilstm_output, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, hidden_size])
else:
log.info("Using without projected attention alignment")
t_context = tf.transpose(r_context, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, token_size])
return output
|
It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper: https:// arxiv. org/ abs/ 1508. 04025 Effective Approaches to Attention - based Neural Machine Translation Args: key: A tensorflow tensor with dimensionality [ None None key_size ] context: A tensorflow tensor with dimensionality [ None None max_num_tokens token_size ] hidden_size: Number of units in hidden representation projected_align: Using dense layer for hidden representation of context. If true between input and attention mechanism insert a dense layer with dimensionality [ hidden_size ]. If false a dense layer is not used. Returns: output: Tensor at the output with dimensionality [ None None hidden_size ]
|
def light_general_attention(key, context, hidden_size, projected_align=False):
""" It is a implementation of the Luong et al. attention mechanism with general score. Based on the paper:
https://arxiv.org/abs/1508.04025 "Effective Approaches to Attention-based Neural Machine Translation"
Args:
key: A tensorflow tensor with dimensionality [None, None, key_size]
context: A tensorflow tensor with dimensionality [None, None, max_num_tokens, token_size]
hidden_size: Number of units in hidden representation
projected_align: Using dense layer for hidden representation of context.
If true, between input and attention mechanism insert a dense layer with dimensionality [hidden_size].
If false, a dense layer is not used.
Returns:
output: Tensor at the output with dimensionality [None, None, hidden_size]
"""
batch_size = tf.shape(context)[0]
max_num_tokens, token_size = context.get_shape().as_list()[-2:]
r_context = tf.reshape(context, shape=[-1, max_num_tokens, token_size])
# projected_key: [None, None, hidden_size]
projected_key = tf.layers.dense(key, hidden_size, kernel_initializer=xav())
r_projected_key = tf.reshape(projected_key, shape=[-1, hidden_size, 1])
# projected context: [None, None, hidden_size]
projected_context = \
tf.layers.dense(r_context, hidden_size, kernel_initializer=xav())
attn = tf.nn.softmax(tf.matmul(projected_context, r_projected_key), dim=1)
if projected_align:
log.info("Using projected attention alignment")
t_context = tf.transpose(projected_context, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, hidden_size])
else:
log.info("Using without projected attention alignment")
t_context = tf.transpose(r_context, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, token_size])
return output
|
It is a implementation of the Bahdanau et al. attention mechanism. Based on the paper: https:// arxiv. org/ abs/ 1409. 0473 Neural Machine Translation by Jointly Learning to Align and Translate Args: key: A tensorflow tensor with dimensionality [ None None key_size ] context: A tensorflow tensor with dimensionality [ None None max_num_tokens token_size ] hidden_size: Number of units in hidden representation projected_align: Using dense layer for hidden representation of context. If true between input and attention mechanism insert a dense layer with dimensionality [ hidden_size ]. If false a dense layer is not used. Returns: output: Tensor at the output with dimensionality [ None None hidden_size ]
|
def light_bahdanau_attention(key, context, hidden_size, projected_align=False):
""" It is a implementation of the Bahdanau et al. attention mechanism. Based on the paper:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
Args:
key: A tensorflow tensor with dimensionality [None, None, key_size]
context: A tensorflow tensor with dimensionality [None, None, max_num_tokens, token_size]
hidden_size: Number of units in hidden representation
projected_align: Using dense layer for hidden representation of context.
If true, between input and attention mechanism insert a dense layer with dimensionality [hidden_size].
If false, a dense layer is not used.
Returns:
output: Tensor at the output with dimensionality [None, None, hidden_size]
"""
batch_size = tf.shape(context)[0]
max_num_tokens, token_size = context.get_shape().as_list()[-2:]
r_context = tf.reshape(context, shape=[-1, max_num_tokens, token_size])
# projected_key: [None, None, hidden_size]
projected_key = tf.layers.dense(key, hidden_size, kernel_initializer=xav())
r_projected_key = \
tf.tile(tf.reshape(projected_key, shape=[-1, 1, hidden_size]),
[1, max_num_tokens, 1])
# projected_context: [None, max_num_tokens, hidden_size]
projected_context = \
tf.layers.dense(r_context, hidden_size, kernel_initializer=xav())
concat_h_state = tf.concat([projected_context, r_projected_key], -1)
projected_state = \
tf.layers.dense(concat_h_state, hidden_size, use_bias=False,
kernel_initializer=xav())
score = \
tf.layers.dense(tf.tanh(projected_state), units=1, use_bias=False,
kernel_initializer=xav())
attn = tf.nn.softmax(score, dim=1)
if projected_align:
log.info("Using projected attention alignment")
t_context = tf.transpose(projected_context, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, hidden_size])
else:
log.info("Using without projected attention alignment")
t_context = tf.transpose(r_context, [0, 2, 1])
output = tf.reshape(tf.matmul(t_context, attn),
shape=[batch_size, -1, token_size])
return output
|
It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers: https:// arxiv. org/ abs/ 1409. 0473 Neural Machine Translation by Jointly Learning to Align and Translate https:// andre - martins. github. io/ docs/ emnlp2017_final. pdf Learning What s Easy: Fully Differentiable Neural Easy - First Taggers Args: key: A tensorflow tensor with dimensionality [ None None key_size ] context: A tensorflow tensor with dimensionality [ None None max_num_tokens token_size ] hidden_size: Number of units in hidden representation depth: Number of csoftmax usages projected_align: Using bidirectional lstm for hidden representation of context. If true beetween input and attention mechanism insert layer of bidirectional lstm with dimensionality [ hidden_size ]. If false bidirectional lstm is not used. Returns: output: Tensor at the output with dimensionality [ None None depth * hidden_size ]
|
def cs_bahdanau_attention(key, context, hidden_size, depth, projected_align=False):
""" It is a implementation of the Bahdanau et al. attention mechanism. Based on the papers:
https://arxiv.org/abs/1409.0473 "Neural Machine Translation by Jointly Learning to Align and Translate"
https://andre-martins.github.io/docs/emnlp2017_final.pdf "Learning What's Easy: Fully Differentiable Neural Easy-First Taggers"
Args:
key: A tensorflow tensor with dimensionality [None, None, key_size]
context: A tensorflow tensor with dimensionality [None, None, max_num_tokens, token_size]
hidden_size: Number of units in hidden representation
depth: Number of csoftmax usages
projected_align: Using bidirectional lstm for hidden representation of context.
If true, beetween input and attention mechanism insert layer of bidirectional lstm with dimensionality [hidden_size].
If false, bidirectional lstm is not used.
Returns:
output: Tensor at the output with dimensionality [None, None, depth * hidden_size]
"""
if hidden_size % 2 != 0:
raise ValueError("hidden size must be dividable by two")
batch_size = tf.shape(context)[0]
max_num_tokens, token_size = context.get_shape().as_list()[-2:]
r_context = tf.reshape(context, shape=[-1, max_num_tokens, token_size])
# projected context: [None, max_num_tokens, token_size]
projected_context = tf.layers.dense(r_context, token_size,
kernel_initializer=xav(),
name='projected_context')
# projected_key: [None, None, hidden_size]
projected_key = tf.layers.dense(key, hidden_size, kernel_initializer=xav(),
name='projected_key')
r_projected_key = \
tf.tile(tf.reshape(projected_key, shape=[-1, 1, hidden_size]),
[1, max_num_tokens, 1])
lstm_fw_cell = tf.nn.rnn_cell.LSTMCell(hidden_size//2)
lstm_bw_cell = tf.nn.rnn_cell.LSTMCell(hidden_size//2)
(output_fw, output_bw), states = \
tf.nn.bidirectional_dynamic_rnn(cell_fw=lstm_fw_cell,
cell_bw=lstm_bw_cell,
inputs=projected_context,
dtype=tf.float32)
# bilstm_output: [-1, max_num_tokens, hidden_size]
bilstm_output = tf.concat([output_fw, output_bw], -1)
concat_h_state = tf.concat([r_projected_key, output_fw, output_bw], -1)
if projected_align:
log.info("Using projected attention alignment")
h_state_for_attn_alignment = bilstm_output
aligned_h_state = csoftmax_attention.attention_bah_block(
concat_h_state, h_state_for_attn_alignment, depth)
output = \
tf.reshape(aligned_h_state, shape=[batch_size, -1, depth * hidden_size])
else:
log.info("Using without projected attention alignment")
h_state_for_attn_alignment = projected_context
aligned_h_state = csoftmax_attention.attention_bah_block(
concat_h_state, h_state_for_attn_alignment, depth)
output = \
tf.reshape(aligned_h_state, shape=[batch_size, -1, depth * token_size])
return output
|
Creates new Generic model by loading existing embedded model into library e. g. from H2O MOJO. The imported model must be supported by H2O.: param file: A string containing path to the file to create the model from: return: H2OGenericEstimator instance representing the generic model
|
def from_file(file=str):
"""
Creates new Generic model by loading existing embedded model into library, e.g. from H2O MOJO.
The imported model must be supported by H2O.
:param file: A string containing path to the file to create the model from
:return: H2OGenericEstimator instance representing the generic model
"""
from h2o import lazy_import, get_frame
model_key = lazy_import(file)
model_bytes_frame = get_frame(model_key[0])
model = H2OGenericEstimator(model_key = model_bytes_frame)
model.train()
return model
|
Extract full regularization path explored during lambda search from glm model.
|
def getGLMRegularizationPath(model):
"""
Extract full regularization path explored during lambda search from glm model.
:param model: source lambda search model
"""
x = h2o.api("GET /3/GetGLMRegPath", data={"model": model._model_json["model_id"]["name"]})
ns = x.pop("coefficient_names")
res = {
"lambdas": x["lambdas"],
"explained_deviance_train": x["explained_deviance_train"],
"explained_deviance_valid": x["explained_deviance_valid"],
"coefficients": [dict(zip(ns, y)) for y in x["coefficients"]],
}
if "coefficients_std" in x:
res["coefficients_std"] = [dict(zip(ns, y)) for y in x["coefficients_std"]]
return res
|
Create a custom GLM model using the given coefficients.
|
def makeGLMModel(model, coefs, threshold=.5):
"""
Create a custom GLM model using the given coefficients.
Needs to be passed source model trained on the dataset to extract the dataset information from.
:param model: source model, used for extracting dataset information
:param coefs: dictionary containing model coefficients
:param threshold: (optional, only for binomial) decision threshold used for classification
"""
model_json = h2o.api(
"POST /3/MakeGLMModel",
data={"model": model._model_json["model_id"]["name"],
"names": list(coefs.keys()),
"beta": list(coefs.values()),
"threshold": threshold}
)
m = H2OGeneralizedLinearEstimator()
m._resolve_model(model_json["model_id"]["name"], model_json)
return m
|
Create H2OCluster object from a list of key - value pairs.
|
def from_kvs(keyvals):
"""
Create H2OCluster object from a list of key-value pairs.
TODO: This method should be moved into the base H2OResponse class.
"""
obj = H2OCluster()
obj._retrieved_at = time.time()
for k, v in keyvals:
if k in {"__meta", "_exclude_fields", "__schema"}: continue
if k in _cloud_v3_valid_keys:
obj._props[k] = v
else:
raise AttributeError("Attribute %s cannot be set on H2OCluster (= %r)" % (k, v))
return obj
|
Shut down the server.
|
def shutdown(self, prompt=False):
"""
Shut down the server.
This method checks if the H2O cluster is still running, and if it does shuts it down (via a REST API call).
:param prompt: A logical value indicating whether to prompt the user before shutting down the H2O server.
"""
if not self.is_running(): return
assert_is_type(prompt, bool)
if prompt:
question = "Are you sure you want to shutdown the H2O instance running at %s (Y/N)? " \
% h2o.connection().base_url
response = input(question) # works in Py2 & Py3 because redefined in h2o.utils.compatibility module
else:
response = "Y"
if response.lower() in {"y", "yes"}:
h2o.api("POST /3/Shutdown")
h2o.connection().close()
|
Determine if the H2O cluster is running or not.
|
def is_running(self):
"""
Determine if the H2O cluster is running or not.
:returns: True if the cluster is up; False otherwise
"""
try:
if h2o.connection().local_server and not h2o.connection().local_server.is_running(): return False
h2o.api("GET /")
return True
except (H2OConnectionError, H2OServerError):
return False
|
Print current cluster status information.
|
def show_status(self, detailed=False):
"""
Print current cluster status information.
:param detailed: if True, then also print detailed information about each node.
"""
if self._retrieved_at + self.REFRESH_INTERVAL < time.time():
# Info is stale, need to refresh
new_info = h2o.api("GET /3/Cloud")
self._fill_from_h2ocluster(new_info)
ncpus = sum(node["num_cpus"] for node in self.nodes)
allowed_cpus = sum(node["cpus_allowed"] for node in self.nodes)
free_mem = sum(node["free_mem"] for node in self.nodes)
unhealthy_nodes = sum(not node["healthy"] for node in self.nodes)
status = "locked" if self.locked else "accepting new members"
if unhealthy_nodes == 0:
status += ", healthy"
else:
status += ", %d nodes are not healthy" % unhealthy_nodes
api_extensions = self.list_api_extensions()
H2ODisplay([
["H2O cluster uptime:", get_human_readable_time(self.cloud_uptime_millis)],
["H2O cluster timezone:", self.cloud_internal_timezone],
["H2O data parsing timezone:", self.datafile_parser_timezone],
["H2O cluster version:", self.version],
["H2O cluster version age:", "{} {}".format(self.build_age, ("!!!" if self.build_too_old else ""))],
["H2O cluster name:", self.cloud_name],
["H2O cluster total nodes:", self.cloud_size],
["H2O cluster free memory:", get_human_readable_bytes(free_mem)],
["H2O cluster total cores:", str(ncpus)],
["H2O cluster allowed cores:", str(allowed_cpus)],
["H2O cluster status:", status],
["H2O connection url:", h2o.connection().base_url],
["H2O connection proxy:", h2o.connection().proxy],
["H2O internal security:", self.internal_security_enabled],
["H2O API Extensions:", ', '.join(api_extensions)],
["Python version:", "%d.%d.%d %s" % tuple(sys.version_info[:4])],
])
if detailed:
keys = ["h2o", "healthy", "last_ping", "num_cpus", "sys_load", "mem_value_size", "free_mem", "pojo_mem",
"swap_mem", "free_disk", "max_disk", "pid", "num_keys", "tcps_active", "open_fds", "rpcs_active"]
header = ["Nodes info:"] + ["Node %d" % (i + 1) for i in range(len(self.nodes))]
table = [[k] for k in keys]
for node in self.nodes:
for i, k in enumerate(keys):
table[i].append(node[k])
H2ODisplay(table=table, header=header)
|
List all jobs performed by the cluster.
|
def list_jobs(self):
"""List all jobs performed by the cluster."""
res = h2o.api("GET /3/Jobs")
table = [["type"], ["dest"], ["description"], ["status"]]
for job in res["jobs"]:
job_dest = job["dest"]
table[0].append(self._translate_job_type(job_dest["type"]))
table[1].append(job_dest["name"])
table[2].append(job["description"])
table[3].append(job["status"])
return table
|
Return the list of all known timezones.
|
def list_timezones(self):
"""Return the list of all known timezones."""
from h2o.expr import ExprNode
return h2o.H2OFrame._expr(expr=ExprNode("listTimeZones"))._frame()
|
Update information in this object from another H2OCluster instance.
|
def _fill_from_h2ocluster(self, other):
"""
Update information in this object from another H2OCluster instance.
:param H2OCluster other: source of the new information for this object.
"""
self._props = other._props
self._retrieved_at = other._retrieved_at
other._props = {}
other._retrieved_at = None
|
Parameters for metalearner algorithm
|
def metalearner_params(self):
"""
Parameters for metalearner algorithm
Type: ``dict`` (default: ``None``).
Example: metalearner_gbm_params = {'max_depth': 2, 'col_sample_rate': 0.3}
"""
if self._parms.get("metalearner_params") != None:
metalearner_params_dict = ast.literal_eval(self._parms.get("metalearner_params"))
for k in metalearner_params_dict:
if len(metalearner_params_dict[k]) == 1: #single parameter
metalearner_params_dict[k] = metalearner_params_dict[k][0]
return metalearner_params_dict
else:
return self._parms.get("metalearner_params")
|
Represent instance of a class as JSON. Arguments: obj -- any object Return: String that represent JSON - encoded object.
|
def check_obj_has_good_numbers(obj, hierarchy="", curr_depth=0, max_depth=4, allowNaN=False):
"""Represent instance of a class as JSON.
Arguments:
obj -- any object
Return:
String that represent JSON-encoded object.
"""
def serialize(obj, hierarchy="", curr_depth=0):
"""Recursively walk object's hierarchy. Limit to max_depth"""
if curr_depth>max_depth:
return
if isinstance(obj, (bool, int, long, float, basestring)):
try:
number = float(obj)
print "Yay!", hierarchy, number
except:
if obj is None:
print "Not Yay! how come you're giving me None for a coefficient? %s %s" % (hierarchy, obj)
elif str(obj)=="":
print "Not Yay! how come you're giving me an empty string for a coefficient? %s %s" % (hierarchy, obj)
else:
raise Exception("%s %s %s is not a valid float" % (hierarchy, obj, type(obj)))
# hack for now
number = 0.0
if not allowNaN and math.isnan(number):
raise Exception("%s %s is a NaN" % (hierarchy, obj))
if not allowNaN and math.isinf(number):
raise Exception("%s %s is a Inf" % (hierarchy, obj))
return number
elif isinstance(obj, dict):
obj = obj.copy()
for key in obj:
obj[key] = serialize(obj[key], hierarchy + ".%" % key, curr_depth+1)
return obj
elif isinstance(obj, (list, tuple)):
return [serialize(item, hierarchy + "[%s]" % i, curr_depth+1) for (i, item) in enumerate(obj)]
elif hasattr(obj, '__dict__'):
return serialize(obj.__dict__, hierarchy, curr_depth+1)
else:
return repr(obj) # Don't know how to handle, convert to string
return (serialize(obj, hierarchy, curr_depth+1))
|
Repeatedly test a function waiting for it to return True.
|
def stabilize(self, test_func, error, timeoutSecs=10, retryDelaySecs=0.5):
'''Repeatedly test a function waiting for it to return True.
Arguments:
test_func -- A function that will be run repeatedly
error -- A function that will be run to produce an error message
it will be called with (node, timeTakenSecs, numberOfRetries)
OR
-- A string that will be interpolated with a dictionary of
{ 'timeTakenSecs', 'numberOfRetries' }
timeoutSecs -- How long in seconds to keep trying before declaring a failure
retryDelaySecs -- How long to wait between retry attempts
'''
start = time.time()
numberOfRetries = 0
while h2o_args.no_timeout or (time.time() - start < timeoutSecs):
if test_func(self, tries=numberOfRetries, timeoutSecs=timeoutSecs):
break
time.sleep(retryDelaySecs)
numberOfRetries += 1
# hey, check the sandbox if we've been waiting a long time...rather than wait for timeout
# to find the badness?. can check_sandbox_for_errors at any time
if ((numberOfRetries % 50) == 0):
check_sandbox_for_errors(python_test_name=h2o_args.python_test_name)
else:
timeTakenSecs = time.time() - start
if isinstance(error, type('')):
raise Exception('%s failed after %.2f seconds having retried %d times' % (
error, timeTakenSecs, numberOfRetries))
else:
msg = error(self, timeTakenSecs, numberOfRetries)
raise Exception(msg)
|
Implements transformation of CALL_FUNCTION bc inst to Rapids expression. The implementation follows definition of behavior defined in https:// docs. python. org/ 3/ library/ dis. html: param nargs: number of arguments including keyword and positional arguments: param idx: index of current instruction on the stack: param ops: stack of instructions: param keys: names of instructions: return: ExprNode representing method call
|
def _call_func_bc(nargs, idx, ops, keys):
"""
Implements transformation of CALL_FUNCTION bc inst to Rapids expression.
The implementation follows definition of behavior defined in
https://docs.python.org/3/library/dis.html
:param nargs: number of arguments including keyword and positional arguments
:param idx: index of current instruction on the stack
:param ops: stack of instructions
:param keys: names of instructions
:return: ExprNode representing method call
"""
named_args = {}
unnamed_args = []
args = []
# Extract arguments based on calling convention for CALL_FUNCTION_KW
while nargs > 0:
if nargs >= 256: # named args ( foo(50,True,x=10) ) read first ( right -> left )
arg, idx = _opcode_read_arg(idx, ops, keys)
named_args[ops[idx][1][0]] = arg
idx -= 1 # skip the LOAD_CONST for the named args
nargs -= 256 # drop 256
else:
arg, idx = _opcode_read_arg(idx, ops, keys)
unnamed_args.insert(0, arg)
nargs -= 1
# LOAD_ATTR <method_name>: Map call arguments to a call of method on H2OFrame class
op = ops[idx][1][0]
args = _get_h2o_frame_method_args(op, named_args, unnamed_args) if is_attr(ops[idx][0]) else []
# Map function name to proper rapids name
op = _get_func_name(op, args)
# Go to next instruction
idx -= 1
if is_bytecode_instruction(ops[idx][0]):
arg, idx = _opcode_read_arg(idx, ops, keys)
args.insert(0, arg)
elif is_load_fast(ops[idx][0]):
args.insert(0, _load_fast(ops[idx][1][0]))
idx -= 1
return [ExprNode(op, *args), idx]
|
Fetch all the jobs or a single job from the/ Jobs endpoint.
|
def jobs(self, job_key=None, timeoutSecs=10, **kwargs):
'''
Fetch all the jobs or a single job from the /Jobs endpoint.
'''
params_dict = {
# 'job_key': job_key
}
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'jobs', True)
result = self.do_json_request('3/Jobs.json', timeout=timeoutSecs, params=params_dict)
return result
|
Poll a single job from the/ Jobs endpoint until it is status: DONE or CANCELLED or FAILED or we time out.
|
def poll_job(self, job_key, timeoutSecs=10, retryDelaySecs=0.5, key=None, **kwargs):
'''
Poll a single job from the /Jobs endpoint until it is "status": "DONE" or "CANCELLED" or "FAILED" or we time out.
'''
params_dict = {}
# merge kwargs into params_dict
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'poll_job', False)
start_time = time.time()
pollCount = 0
while True:
result = self.do_json_request('3/Jobs.json/' + job_key, timeout=timeoutSecs, params=params_dict)
# print 'Job: ', dump_json(result)
if key:
frames_result = self.frames(key=key)
print 'frames_result for key:', key, dump_json(result)
jobs = result['jobs'][0]
description = jobs['description']
dest = jobs['dest']
dest_name = dest['name']
msec = jobs['msec']
status = jobs['status']
progress = jobs['progress']
print description, \
"dest_name:", dest_name, \
"\tprogress:", "%-10s" % progress, \
"\tstatus:", "%-12s" % status, \
"\tmsec:", msec
if status=='DONE' or status=='CANCELLED' or status=='FAILED':
h2o_sandbox.check_sandbox_for_errors()
return result
# what about 'CREATED'
# FIX! what are the other legal polling statuses that we should check for?
if not h2o_args.no_timeout and (time.time() - start_time > timeoutSecs):
h2o_sandbox.check_sandbox_for_errors()
emsg = "Job:", job_key, "timed out in:", timeoutSecs
# for debug
a = h2o.nodes[0].get_cloud()
print "cloud.json:", dump_json(a)
raise Exception(emsg)
print emsg
return None
# check every other poll, for now
if (pollCount % 2) == 0:
h2o_sandbox.check_sandbox_for_errors()
time.sleep(retryDelaySecs)
pollCount += 1
|
Import a file or files into h2o. The file parameter accepts a directory or a single file. 192. 168. 0. 37: 54323/ ImportFiles. html?file = %2Fhome%2F0xdiag%2Fdatasets
|
def import_files(self, path, timeoutSecs=180):
'''
Import a file or files into h2o. The 'file' parameter accepts a directory or a single file.
192.168.0.37:54323/ImportFiles.html?file=%2Fhome%2F0xdiag%2Fdatasets
'''
a = self.do_json_request('3/ImportFiles.json',
timeout=timeoutSecs,
params={"path": path}
)
verboseprint("\nimport_files result:", dump_json(a))
h2o_sandbox.check_sandbox_for_errors()
return a
|
Parse an imported raw file or files into a Frame.
|
def parse(self, key, hex_key=None, columnTypeDict=None,
timeoutSecs=300, retryDelaySecs=0.2, initialDelaySecs=None, pollTimeoutSecs=180,
noise=None, benchmarkLogging=None, noPoll=False, intermediateResults=False, **kwargs):
'''
Parse an imported raw file or files into a Frame.
'''
# these should override what parse setup gets below
params_dict = {
'source_frames': None,
'destination_frame': hex_key,
'parse_type': None, # file type
'separator': None,
'single_quotes': None,
'check_header': None, # forces first line to be seen as column names
'number_columns': None,
'column_names': None, # a list
'column_types': None, # a list. or can use columnTypeDict param (see below)
'na_strings' : None, # a list
'chunk_size': None,
# are these two no longer supported?
'delete_on_done': None,
'blocking': None,
}
# if key is a list, create a comma separated string
# list or tuple but not string
if not isinstance(key, basestring):
# it's a list of some kind (tuple ok?)
# if len(key) > 1:
# print "I noticed you're giving me a list of > 1 keys %s to parse:" % len(key), key
# len 1 is ok here. 0 not. what if None or [None] here
if not key:
raise Exception("key seems to be bad in parse. Should be list or string. %s" % key)
# have to put double quotes around the individual list items (single not legal)
source_frames = "[" + ",".join(map((lambda x: '"' + x + '"'), key)) + "]"
else:
# what if None here
source_frames = '["' + key + '"]' # quotes required on key
params_dict['source_frames'] = source_frames
# merge kwargs into params_dict
# =None overwrites params_dict
# columnTypeDict not used here
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'parse before setup merge', print_params=False)
# Call ParseSetup?source_frames=[keys] . . .
# if benchmarkLogging:
# cloudPerfH2O.get_log_save(initOnly=True)
# h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'parse_setup', print_params=True)
params_setup = {'source_frames': source_frames}
setup_result = self.do_json_request(jsonRequest="3/ParseSetup.json", cmd='post', timeout=timeoutSecs, postData=params_setup)
h2o_sandbox.check_sandbox_for_errors()
verboseprint("ParseSetup result:", dump_json(setup_result))
# this should match what we gave as input?
if setup_result['source_frames']:
# should these be quoted?
source_framesStr = "[" + ",".join([('"%s"' % src['name']) for src in setup_result['source_frames'] ]) + "]"
else:
source_framesStr = None
# I suppose we need a way for parameters to parse() to override these
# should it be an array or a dict?
if setup_result['column_names']:
# single quotes not legal..need double quotes
columnNamesStr = "[" + ",".join(map((lambda x: '"' + x + '"'), setup_result['column_names'])) + "]"
else:
columnNamesStr = None
columnTypes = setup_result['column_types']
assert columnTypes is not None, "%s %s" % ("column_types:", columnTypes)
if setup_result['na_strings']:
# single quotes not legal..need double quotes
naStrings = "[" + ",".join(map((lambda x: '"' + x + '"' if x != None else '""'), setup_result['na_strings'])) + "]"
else:
naStrings = None
# dict parameter to update columnTypeDict?
# but we don't pass columnNames like this?
ct = setup_result['column_types']
columnNames = setup_result['column_names']
if columnTypeDict:
for k,v in columnTypeDict.iteritems():
if isinstance(k, int):
# if a column index
if k>=0 and k<len(ct):
ct[k] = v
else:
raise Exception("bad col index %s in columnTypeDict param %s" % (k, columnTypeDict))
# if a column name
elif isinstance(k, basestring):
# find the index
if k not in columnNames:
raise Exception("bad col name %s in columnTypeDict param %s. columnNames: %s" % (k, columnTypeDict, columnNames))
ci = columnNames.index(k)
ct[ci] = v
else:
raise Exception("%s %s should be int or string" % (k, type(k)))
columnTypesStr = "[" + ",".join(map((lambda x: '"' + x + '"'), ct)) + "]"
parse_params = {
'source_frames': source_framesStr,
'destination_frame': setup_result['destination_frame'],
'parse_type': setup_result['parse_type'],
'separator': setup_result['separator'],
'single_quotes': setup_result['single_quotes'],
'check_header': setup_result['check_header'],
'number_columns': setup_result['number_columns'],
'column_names': columnNamesStr,
'column_types': columnTypesStr,
'na_strings': naStrings,
'chunk_size': setup_result['chunk_size'],
# No longer supported? how come these aren't in setup_result?
'delete_on_done': params_dict['delete_on_done'],
'blocking': params_dict['blocking'],
}
# HACK: if there are too many column names..don't print! it is crazy output
# just check the output of parse setup. Don't worry about columnNames passed as params here.
tooManyColNamesToPrint = setup_result['column_names'] and len(setup_result['column_names']) > 2000
if tooManyColNamesToPrint:
h2p.yellow_print("Not printing the parameters to Parse because the columnNames are too lengthy.")
h2p.yellow_print("See sandbox/commands.log")
# merge params_dict into parse_params
# don't want =None to overwrite parse_params
h2o_methods.check_params_update_kwargs(parse_params, params_dict, 'parse after merge into parse setup',
print_params=not tooManyColNamesToPrint, ignoreNone=True)
print "parse source_frames is length:", len(parse_params['source_frames'])
# This can be null now? parseSetup doesn't return default colnames?
# print "parse column_names is length:", len(parse_params['column_names'])
# none of the kwargs passed to here!
parse_result = self.do_json_request( jsonRequest="3/Parse.json", cmd='post', postData=parse_params, timeout=timeoutSecs)
verboseprint("Parse result:", dump_json(parse_result))
job_key = parse_result['job']['key']['name']
hex_key = parse_params['destination_frame']
# TODO: dislike having different shapes for noPoll and poll
if noPoll:
# ??
h2o_sandbox.check_sandbox_for_errors()
# return self.jobs(job_key)
return parse_result
# does Frame also, while polling
if intermediateResults:
key = hex_key
else:
key = None
job_result = self.poll_job(job_key, timeoutSecs=timeoutSecs, key=key)
if job_result:
jobs = job_result['jobs'][0]
description = jobs['description']
dest = jobs['dest']
msec = jobs['msec']
status = jobs['status']
progress = jobs['progress']
dest_key = dest['name']
# can condition this with a parameter if some FAILED are expected by tests.
if status=='FAILED':
print dump_json(job_result)
raise Exception("Taking exception on parse job status: %s %s %s %s %s" % \
(status, progress, msec, dest_key, description))
return self.frames(dest_key)
else:
# ? we should always get a job_json result
raise Exception("parse didn't get a job_result when it expected one")
|
Return a single Frame or all of the Frames in the h2o cluster. The frames are contained in a list called frames at the top level of the result. Currently the list is unordered. TODO: When find_compatible_models is implemented then the top level dict will also contain a models list.
|
def frames(self, key=None, timeoutSecs=60, **kwargs):
if not (key is None or isinstance(key, (basestring, Key))):
raise Exception("frames: key should be string or Key type %s %s" % (type(key), key))
params_dict = {
'find_compatible_models': 0,
'row_offset': 0, # is offset working yet?
'row_count': 5,
}
'''
Return a single Frame or all of the Frames in the h2o cluster. The
frames are contained in a list called "frames" at the top level of the
result. Currently the list is unordered.
TODO:
When find_compatible_models is implemented then the top level
dict will also contain a "models" list.
'''
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'frames', False)
# key can be type Key? (from h2o_xl) str(key) should return
if key:
if isinstance(key, Key):
keyStr = key.frame
else:
keyStr = key
result = self.do_json_request('3/Frames.json/' + keyStr, timeout=timeoutSecs, params=params_dict)
else:
result = self.do_json_request('3/Frames.json', timeout=timeoutSecs, params=params_dict)
return result
|
Return the summary for a single column for a single Frame in the h2o cluster.
|
def summary(self, key, column="C1", timeoutSecs=10, **kwargs):
'''
Return the summary for a single column for a single Frame in the h2o cluster.
'''
params_dict = {
# 'offset': 0,
# 'len': 100
}
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'summary', True)
result = self.do_json_request('3/Frames.json/%s/columns/%s/summary' % (key, column), timeout=timeoutSecs, params=params_dict)
h2o_sandbox.check_sandbox_for_errors()
return result
|
Delete a frame on the h2o cluster given its key.
|
def delete_frame(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs):
'''
Delete a frame on the h2o cluster, given its key.
'''
assert key is not None, '"key" parameter is null'
result = self.do_json_request('/3/Frames.json/' + key, cmd='delete', timeout=timeoutSecs)
# TODO: look for what?
if not ignoreMissingKey and 'f00b4r' in result:
raise ValueError('Frame key not found: ' + key)
return result
|
Return a model builder or all of the model builders known to the h2o cluster. The model builders are contained in a dictionary called model_builders at the top level of the result. The dictionary maps algorithm names to parameters lists. Each of the parameters contains all the metdata required by a client to present a model building interface to the user.
|
def model_builders(self, algo=None, timeoutSecs=10, **kwargs):
'''
Return a model builder or all of the model builders known to the
h2o cluster. The model builders are contained in a dictionary
called "model_builders" at the top level of the result. The
dictionary maps algorithm names to parameters lists. Each of the
parameters contains all the metdata required by a client to
present a model building interface to the user.
if parameters = True, return the parameters?
'''
params_dict = {}
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'model_builders', False)
request = '3/ModelBuilders.json'
if algo:
request += "/" + algo
result = self.do_json_request(request, timeout=timeoutSecs, params=params_dict)
# verboseprint(request, "result:", dump_json(result))
h2o_sandbox.check_sandbox_for_errors()
return result
|
Check a dictionary of model builder parameters on the h2o cluster using the given algorithm and model parameters.
|
def validate_model_parameters(self, algo, training_frame, parameters, timeoutSecs=60, **kwargs):
'''
Check a dictionary of model builder parameters on the h2o cluster
using the given algorithm and model parameters.
'''
assert algo is not None, '"algo" parameter is null'
# Allow this now: assert training_frame is not None, '"training_frame" parameter is null'
assert parameters is not None, '"parameters" parameter is null'
model_builders = self.model_builders(timeoutSecs=timeoutSecs)
assert model_builders is not None, "/ModelBuilders REST call failed"
assert algo in model_builders['model_builders']
builder = model_builders['model_builders'][algo]
# TODO: test this assert, I don't think this is working. . .
if training_frame is not None:
frames = self.frames(key=training_frame)
assert frames is not None, "/Frames/{0} REST call failed".format(training_frame)
key_name = frames['frames'][0]['key']['name']
assert key_name==training_frame, \
"/Frames/{0} returned Frame {1} rather than Frame {2}".format(training_frame, key_name, training_frame)
parameters['training_frame'] = training_frame
# TODO: add parameter existence checks
# TODO: add parameter value validation
# FIX! why ignoreH2oError here?
result = self.do_json_request('/3/ModelBuilders.json/' + algo + "/parameters", cmd='post',
timeout=timeoutSecs, postData=parameters, ignoreH2oError=True, noExtraErrorCheck=True)
verboseprint("model parameters validation: " + repr(result))
return result
|
Build a model on the h2o cluster using the given algorithm training Frame and model parameters.
|
def build_model(self, algo, training_frame, parameters, destination_frame=None, model_id=None,
timeoutSecs=60, noPoll=False, **kwargs):
if 'destination_key' in kwargs:
raise Exception('Change destination_key in build_model() to model_id')
'''
Build a model on the h2o cluster using the given algorithm, training
Frame and model parameters.
'''
assert algo is not None, '"algo" parameter is null'
assert training_frame is not None, '"training_frame" parameter is null'
assert parameters is not None, '"parameters" parameter is null'
# why always check that the algo is in here?
model_builders = self.model_builders(timeoutSecs=timeoutSecs)
assert model_builders is not None, "/ModelBuilders REST call failed"
assert algo in model_builders['model_builders'], "%s %s" % (algo, [k for k in model_builders['model_builders']])
builder = model_builders['model_builders'][algo]
# TODO: test this assert, I don't think this is working. . .
frames = self.frames(key=training_frame)
assert frames is not None, "/Frames/{0} REST call failed".format(training_frame)
key_name = frames['frames'][0]['frame_id']['name']
assert key_name==training_frame, \
"/Frames/{0} returned Frame {1} rather than Frame {2}".format(training_frame, key_name, training_frame)
parameters['training_frame'] = training_frame
if destination_frame is not None:
print "destination_frame should be replaced by model_id now"
parameters['model_id'] = destination_frame
if model_id is not None:
parameters['model_id'] = model_id
print "build_model parameters", parameters
start = time.time()
result1 = self.do_json_request('/3/ModelBuilders.json/' + algo, cmd='post',
timeout=timeoutSecs, postData=parameters)
# make get overwritten after polling
elapsed = time.time() - start
verboseprint("build_model result", dump_json(result1))
if noPoll:
result = result1
elif ('validation_error_count' in result1) and (result1['validation_error_count']>0):
h2p.yellow_print("parameter error in model_builders: %s" % result1)
# parameters validation failure
# TODO: add schema_type and schema_version into all the schemas to make this clean to check
result = result1
# don't bother printing a time message
elif 'exception_msg' in result1:
h2p.yellow_print("exception msg in model_builders: %s" % result1['exception_msg'])
result = result1
else:
job_result = result1['job']
job_key = job_result['key']['name']
verboseprint("build_model job_key: " + repr(job_key))
job_result = self.poll_job(job_key, timeoutSecs=timeoutSecs)
verboseprint(job_result)
elapsed = time.time() - start
print "ModelBuilders", algo, "end on", training_frame, 'took', time.time() - start, 'seconds'
print "%d pct. of timeout" % ((elapsed/timeoutSecs) * 100)
if job_result:
jobs = job_result['jobs'][0]
description = jobs['description']
dest = jobs['dest']
msec = jobs['msec']
status = jobs['status']
progress = jobs['progress']
# can condition this with a parameter if some FAILED are expected by tests.
if status=='FAILED':
print dump_json(job_result)
raise Exception("Taking exception on build_model job status: %s %s %s %s" % \
(status, progress, msec, description))
result = job_result
else:
# ? we should always get a job_json result
raise Exception("build_model didn't get a job_result when it expected one")
# return None
verboseprint("result:", result)
h2o_sandbox.check_sandbox_for_errors()
result['python_elapsed'] = elapsed
return result
|
Score a model on the h2o cluster on the given Frame and return only the model metrics.
|
def compute_model_metrics(self, model, frame, timeoutSecs=60, **kwargs):
'''
Score a model on the h2o cluster on the given Frame and return only the model metrics.
'''
assert model is not None, '"model" parameter is null'
assert frame is not None, '"frame" parameter is null'
models = self.models(key=model, timeoutSecs=timeoutSecs)
assert models is not None, "/Models REST call failed"
assert models['models'][0]['model_id']['name'] == model, "/Models/{0} returned Model {1} rather than Model {2}".format(model, models['models'][0]['key']['name'], model)
# TODO: test this assert, I don't think this is working. . .
frames = self.frames(key=frame)
assert frames is not None, "/Frames/{0} REST call failed".format(frame)
print "frames:", dump_json(frames)
# is the name not there?
# assert frames['frames'][0]['model_id']['name'] == frame, "/Frames/{0} returned Frame {1} rather than Frame {2}".format(frame, models['models'][0]['key']['name'], frame)
result = self.do_json_request('/3/ModelMetrics.json/models/' + model + '/frames/' + frame, cmd='post', timeout=timeoutSecs)
mm = result['model_metrics'][0]
verboseprint("model metrics: " + repr(mm))
h2o_sandbox.check_sandbox_for_errors()
return mm
|
ModelMetrics list.
|
def model_metrics(self, timeoutSecs=60, **kwargs):
'''
ModelMetrics list.
'''
result = self.do_json_request('/3/ModelMetrics.json', cmd='get', timeout=timeoutSecs)
h2o_sandbox.check_sandbox_for_errors()
return result
|
Return all of the models in the h2o cluster or a single model given its key. The models are contained in a list called models at the top level of the result. Currently the list is unordered. TODO: When find_compatible_frames is implemented then the top level dict will also contain a frames list.
|
def models(self, key=None, timeoutSecs=10, **kwargs):
'''
Return all of the models in the h2o cluster, or a single model given its key.
The models are contained in a list called "models" at the top level of the
result. Currently the list is unordered.
TODO:
When find_compatible_frames is implemented then the top level
dict will also contain a "frames" list.
'''
params_dict = {
'find_compatible_frames': False
}
h2o_methods.check_params_update_kwargs(params_dict, kwargs, 'models', True)
if key:
# result = self.do_json_request('3/Models.json', timeout=timeoutSecs, params=params_dict)
# print "for ray:", dump_json(result)
result = self.do_json_request('3/Models.json/' + key, timeout=timeoutSecs, params=params_dict)
else:
result = self.do_json_request('3/Models.json', timeout=timeoutSecs, params=params_dict)
verboseprint("models result:", dump_json(result))
h2o_sandbox.check_sandbox_for_errors()
return result
|
Delete a model on the h2o cluster given its key.
|
def delete_model(self, key, ignoreMissingKey=True, timeoutSecs=60, **kwargs):
'''
Delete a model on the h2o cluster, given its key.
'''
assert key is not None, '"key" parameter is null'
result = self.do_json_request('/3/Models.json/' + key, cmd='delete', timeout=timeoutSecs)
# TODO: look for what?
if not ignoreMissingKey and 'f00b4r' in result:
raise ValueError('Model key not found: ' + key)
verboseprint("delete_model result:", dump_json(result))
return result
|
Pretty tabulated string of all the cached data and column names
|
def _tabulate(self, tablefmt="simple", rollups=False, rows=10):
"""Pretty tabulated string of all the cached data, and column names"""
if not self.is_valid(): self.fill(rows=rows)
# Pretty print cached data
d = collections.OrderedDict()
# If also printing the rollup stats, build a full row-header
if rollups:
col = next(iter(viewvalues(self._data))) # Get a sample column
lrows = len(col['data']) # Cached rows being displayed
d[""] = ["type", "mins", "mean", "maxs", "sigma", "zeros", "missing"] + list(map(str, range(lrows)))
# For all columns...
for k, v in viewitems(self._data):
x = v['data'] # Data to display
t = v["type"] # Column type
if t == "enum":
domain = v['domain'] # Map to cat strings as needed
x = ["" if math.isnan(idx) else domain[int(idx)] for idx in x]
elif t == "time":
x = ["" if math.isnan(z) else time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(z / 1000)) for z in x]
if rollups: # Rollups, if requested
mins = v['mins'][0] if v['mins'] and v["type"] != "enum" else None
maxs = v['maxs'][0] if v['maxs'] and v["type"] != "enum" else None
#Cross check type with mean and sigma. Set to None if of type enum.
if v['type'] == "enum":
v['mean'] = v['sigma'] = v['zero_count'] = None
x = [v['type'], mins, v['mean'], maxs, v['sigma'], v['zero_count'], v['missing_count']] + x
d[k] = x # Insert into ordered-dict
return tabulate.tabulate(d, headers="keys", tablefmt=tablefmt)
|
Create a new reservation for count instances
|
def run_instances(count, ec2_config, region, waitForSSH=True, tags=None):
'''Create a new reservation for count instances'''
ec2params = inheritparams(ec2_config, EC2_API_RUN_INSTANCE)
ec2params.setdefault('min_count', count)
ec2params.setdefault('max_count', count)
reservation = None
conn = ec2_connect(region)
try:
reservation = conn.run_instances(**ec2params)
log('Reservation: {0}'.format(reservation.id))
log('Waiting for {0} EC2 instances {1} to come up, this can take 1-2 minutes.'.format(len(reservation.instances), reservation.instances))
start = time.time()
time.sleep(1)
for instance in reservation.instances:
while instance.update() == 'pending':
time.sleep(1)
h2o_cmd.dot()
if not instance.state == 'running':
raise Exception('\033[91m[ec2] Error waiting for running state. Instance is in state {0}.\033[0m'.format(instance.state))
log('Instances started in {0} seconds'.format(time.time() - start))
log('Instances: ')
for inst in reservation.instances: log(" {0} ({1}) : public ip: {2}, private ip: {3}".format(inst.public_dns_name, inst.id, inst.ip_address, inst.private_ip_address))
if waitForSSH:
# kbn: changing to private address, so it should fail if not in right domain
# used to have the public ip address
wait_for_ssh([ i.private_ip_address for i in reservation.instances ])
# Tag instances
try:
if tags:
conn.create_tags([i.id for i in reservation.instances], tags)
except:
warn('Something wrong during tagging instances. Exceptions IGNORED!')
print sys.exc_info()
pass
return reservation
except:
print "\033[91mUnexpected error\033[0m :", sys.exc_info()
if reservation:
terminate_reservation(reservation, region)
raise
|
terminate all the instances given by its ids
|
def terminate_instances(instances, region):
'''terminate all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Terminating instances {0}.".format(instances))
conn.terminate_instances(instances)
log("Done")
|
stop all the instances given by its ids
|
def stop_instances(instances, region):
'''stop all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Stopping instances {0}.".format(instances))
conn.stop_instances(instances)
log("Done")
|
Start all the instances given by its ids
|
def start_instances(instances, region):
'''Start all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Starting instances {0}.".format(instances))
conn.start_instances(instances)
log("Done")
|
Reboot all the instances given by its ids
|
def reboot_instances(instances, region):
'''Reboot all the instances given by its ids'''
if not instances: return
conn = ec2_connect(region)
log("Rebooting instances {0}.".format(instances))
conn.reboot_instances(instances)
log("Done")
|
Wait for ssh service to appear on given hosts
|
def wait_for_ssh(ips, port=22, skipAlive=True, requiredsuccess=3):
''' Wait for ssh service to appear on given hosts'''
log('Waiting for SSH on following hosts: {0}'.format(ips))
for ip in ips:
if not skipAlive or not ssh_live(ip, port):
log('Waiting for SSH on instance {0}...'.format(ip))
count = 0
while count < requiredsuccess:
if ssh_live(ip, port):
count += 1
else:
count = 0
time.sleep(1)
h2o_cmd.dot()
|
This is an advanced exception - handling hook function that is designed to supercede the standard Python s exception handler. It offers several enhancements: * Clearer and more readable format for the exception message and the traceback. * Decorators are filtered out from the traceback ( if they declare their implementation function to have name decorator_invisible ). * Local variables in all execution frames are also printed out. * Print out server - side stacktrace for exceptions that carry this information ( e. g. H2OServerError ).
|
def _except_hook(exc_type, exc_value, exc_tb):
"""
This is an advanced exception-handling hook function, that is designed to supercede the standard Python's
exception handler. It offers several enhancements:
* Clearer and more readable format for the exception message and the traceback.
* Decorators are filtered out from the traceback (if they declare their implementation function to
have name "decorator_invisible").
* Local variables in all execution frames are also printed out.
* Print out server-side stacktrace for exceptions that carry this information (e.g. H2OServerError).
Some documentation about the objects used herein:
"traceback" type (types.TracebackType): -- stack traceback of an exception
tb_frame: execution frame object at the current level
tb_lasti: index of the last attempted instruction in the bytecode
tb_lineno: line number in the source code
tb_next: next level in the traceback stack (towards the frame where exception occurred)
"frame" type (types.FrameType): -- the execution frame
f_back: previous stack frame (toward the caller)
f_code: code object being executed
f_locals: dictionary of all local variables
f_globals: dictionary of all global variables
f_builtins: dictionary of built-in names
f_lineno: line number
f_lasti: current instruction being executed (index into the f_code.co_code)
f_restricted: ?
f_trace: (function) function called at the start of each code line (settable!)
f_exc_type, f_exc_value, f_exc_traceback: [Py2 only] most recent exception triple
"code" type (types.CodeType): -- byte-compiled code
co_name: function name
co_argcount: number of positional arguments
co_nlocals: number of local variables inside the function
co_varnames: names of all local variables
co_cellvars: names of variables referenced by nested functions
co_freevars: names of free variables used by nested functions
co_code: raw bytecode
co_consts: literals used in the bytecode
co_names: names used in the bytecode
co_filename: name of the file that contains the function
co_firstlineno: line number where the function starts
co_lnotab: encoded offsets to line numbers within the bytecode
co_stacksize: required stack size
co_flags: function flags. Bit 2 = function uses *args; bit 3 = function uses **kwargs
Note that when the Python code re-raises an exception (by calling `raise` without arguments, which semantically
means "raise the exception again as if it wasn't caught"), then tb.tb_lineno will contain the line number of the
original exception, whereas tb.tb_frame.f_lineno will be the line number where the exception was re-raised.
:param exc_type: exception class
:param exc_value: the exception instance object
:param exc_tb: stacktrace at the point of the exception. The "traceback" type is actually a linked list,
and this object represents the beginning of this list (i.e. corresponds to the execution
frame of the outermost expression being evaluated). We need to walk down the list (by repeatedly
moving to exc_tb.tb_next) in order to find the execution frame where the actual exception occurred.
"""
if isinstance(exc_value, H2OJobCancelled):
return
if isinstance(exc_value, H2OSoftError):
_handle_soft_error(exc_type, exc_value, exc_tb)
else:
_prev_except_hook(exc_type, exc_value, exc_tb)
# Everythin else is disabled for now, because it generates too much output due to bugs in H2OFrame implementation
return
import linecache
if not exc_tb: # Happens on SyntaxError exceptions
sys.__excepthook__(exc_type, exc_value, exc_tb)
return
get_tb.tb = exc_tb
err("\n================================ EXCEPTION INFO ================================\n")
if exc_type != type(exc_value):
err("Exception type(s): %s / %s" % (exc_type, type(exc_value)))
# If the exception contains .stacktrace attribute (representing server-side stack trace) then print it too.
for arg in exc_value.args:
if hasattr(arg, "stacktrace"):
err("[SERVER STACKTRACE]")
for line in arg.stacktrace:
err(" %s" % line.strip())
err()
# Print local frames
err("[LOCAL FRAMES]")
err("Omitted: imported modules, class declarations, __future__ features, None-valued")
tb = exc_tb
while tb:
tb_line = tb.tb_lineno
frame = tb.tb_frame
frame_file = frame.f_code.co_filename
frame_func = frame.f_code.co_name
frame_locl = frame.f_locals
tb = tb.tb_next
if frame_func == "decorator_invisible": continue
if frame_func == "__getattribute__": continue
if not frame_locl: continue
err("\n Within %s() line %s in file %s:" % (frame_func, tb_line, frame_file))
for key in sorted(viewkeys(frame_locl), reverse=True):
if key.startswith("__") and key.endswith("__"): continue
value = frame_locl[key]
if value is None: continue # do not print uninitialized variables
if hasattr(value, "__class__"):
if value.__class__ is ModuleType: continue # omit imported modules
if value.__class__ is type: continue # omit class declarations (new-style classes only)
if value.__class__ is print_function.__class__: continue # omit __future__ declarations
try:
strval = str(value)
n_lines = strval.count("\n")
if n_lines > 1:
strval = "%s... (+ %d line%s)" % (strval[:strval.index("\n")], n_lines - 1,
"s" if n_lines > 2 else "")
err("%25s: %s" % (key, strval))
except:
err("%25s: <UNABLE TO PRINT VALUE>" % key)
err()
# Print the traceback
err("[STACKTRACE]")
last_file = None
tb = exc_tb
prev_info = None
skip_frames = 0
while tb:
tb_lineno = tb.tb_lineno
frame = tb.tb_frame
frame_file = frame.f_code.co_filename
frame_func = frame.f_code.co_name
frame_glob = frame.f_globals
tb = tb.tb_next
if frame_func == "decorator_invisible": continue
if frame_func == "__getattribute__": continue
if (tb_lineno, frame_file) == prev_info:
skip_frames += 1
continue
else:
if skip_frames:
err(" %20s ... +%d nested calls" % ("", skip_frames))
skip_frames = 0
prev_info = (tb_lineno, frame_file)
if frame_file != last_file:
last_file = frame_file
err("\n File %s:" % frame_file)
line_txt = linecache.getline(frame_file, tb_lineno, frame_glob)
err(" %20s() #%04d %s" % (frame_func, tb_lineno, line_txt.strip()))
if skip_frames:
err(" %20s ... +%d nested calls" % ("", skip_frames))
err()
# Print the exception message
tb = exc_tb
while tb.tb_next:
tb = tb.tb_next
print("[EXCEPTION]", file=sys.stderr)
print(" %s: %s" % (exc_value.__class__.__name__, str(exc_value)), file=sys.stderr)
print(" at line %d in %s\n" % (tb.tb_lineno, tb.tb_frame.f_code.co_filename), file=sys.stderr)
# There was a warning in {https://docs.python.org/2/library/sys.html} that storing traceback object in a local
# variable may cause a circular reference; so we explicitly delete these vars just in case.
del tb
del exc_tb
|
Return fully qualified function name.
|
def _get_method_full_name(func):
"""
Return fully qualified function name.
This method will attempt to find "full name" of the given function object. This full name is either of
the form "<class name>.<method name>" if the function is a class method, or "<module name>.<func name>"
if it's a regular function. Thus, this is an attempt to back-port func.__qualname__ to Python 2.
:param func: a function object.
:returns: string with the function's full name as explained above.
"""
# Python 3.3 already has this information available...
if hasattr(func, "__qualname__"): return func.__qualname__
module = inspect.getmodule(func)
if module is None:
return "?.%s" % getattr(func, "__name__", "?")
for cls_name in dir(module):
cls = getattr(module, cls_name)
if not inspect.isclass(cls): continue
for method_name in dir(cls):
cls_method = getattr(cls, method_name)
if cls_method == func:
return "%s.%s" % (cls_name, method_name)
if hasattr(func, "__name__"):
return "%s.%s" % (module.__name__, func.__name__)
return "<unknown>"
|
Given a frame and a compiled function code find the corresponding function object within the frame.
|
def _find_function_from_code(frame, code):
"""
Given a frame and a compiled function code, find the corresponding function object within the frame.
This function addresses the following problem: when handling a stacktrace, we receive information about
which piece of code was being executed in the form of a CodeType object. That objects contains function name,
file name, line number, and the compiled bytecode. What it *doesn't* contain is the function object itself.
So this utility function aims at locating this function object, and it does so by searching through objects
in the preceding local frame (i.e. the frame where the function was called from). We expect that the function
should usually exist there -- either by itself, or as a method on one of the objects.
:param types.FrameType frame: local frame where the function ought to be found somewhere.
:param types.CodeType code: the compiled code of the function to look for.
:returns: the function object, or None if not found.
"""
def find_code(iterable, depth=0):
if depth > 3: return # Avoid potential infinite loops, or generally objects that are too deep.
for item in iterable:
if item is None: continue
found = None
if hasattr(item, "__code__") and item.__code__ == code:
found = item
elif isinstance(item, type) or isinstance(item, ModuleType): # class / module
try:
found = find_code((getattr(item, n, None) for n in dir(item)), depth + 1)
except Exception:
# Sometimes merely getting module's attributes may cause an exception. For example :mod:`six.moves`
# is such an offender...
continue
elif isinstance(item, (list, tuple, set)):
found = find_code(item, depth + 1)
elif isinstance(item, dict):
found = find_code(item.values(), depth + 1)
if found: return found
return find_code(frame.f_locals.values()) or find_code(frame.f_globals.values())
|
Return function s declared arguments as a string.
|
def _get_args_str(func, highlight=None):
"""
Return function's declared arguments as a string.
For example for this function it returns "func, highlight=None"; for the ``_wrap`` function it returns
"text, wrap_at=120, indent=4". This should usually coincide with the function's declaration (the part
which is inside the parentheses).
"""
if not func: return ""
s = str(inspect.signature(func))[1:-1]
if highlight:
s = re.sub(r"\b%s\b" % highlight, Style.BRIGHT + Fore.WHITE + highlight + Fore.LIGHTBLACK_EX + Style.NORMAL, s)
return s
|
Return piece of text wrapped around if needed.
|
def _wrap(text, wrap_at=120, indent=4):
"""
Return piece of text, wrapped around if needed.
:param text: text that may be too long and then needs to be wrapped.
:param wrap_at: the maximum line length.
:param indent: number of spaces to prepend to all subsequent lines after the first.
"""
out = ""
curr_line_length = indent
space_needed = False
for word in text.split():
if curr_line_length + len(word) > wrap_at:
out += "\n" + " " * indent
curr_line_length = indent
space_needed = False
if space_needed:
out += " "
curr_line_length += 1
out += word
curr_line_length += len(word)
space_needed = True
return out
|
input: jenkins environment variable EXECUTOR_NUMBER output: creates./ BASE_PORT. sh that you should source./ PORT. sh ( can t see the env. variables directly from python? )
|
def jenkins_h2o_port_allocate():
"""
input: jenkins environment variable EXECUTOR_NUMBER
output: creates ./BASE_PORT.sh, that you should 'source ./PORT.sh'
(can't see the env. variables directly from python?)
which will create os environment variables H2O_PORT and H2O_PORT_OFFSET (legacy)
internal state for this script that can be updated:
USED_HOSTNAMES (list of machine names),
PORTS_PER_SLOT (max per any job),
DEFAULT_BASE_PORT
If you modify any of the internal state, you may introduce contention between
new jenkins jobs and running jenkins jobs. (might not!)
You should stop/start all jobs (or ignore failures) if you modify internal state here.
Hence, no parameters to avoid living dangerously!
"""
if os.environ.has_key("EXECUTOR_NUMBER"):
# this will fail if it's not an integer
executor = int(os.environ["EXECUTOR_NUMBER"])
else:
executor = 1 # jenkins starts with 1
print "jenkins EXECUTOR_NUMBER:", executor
if executor<0 or executor>=EXECUTOR_NUM:
raise Exception("executor: %s wrong? Expecting 1-8 jenkins executors on a machine (0-7 exp.)" % executor)
h2oPort = DEFAULT_BASE_PORT
h2oPortOffset = 0
hostname = socket.gethostname()
if hostname not in USED_HOSTNAMES:
print "WARNING: this hostname: %s isn't in my list. You should add it?" % hostname
print "Will use default base port"
else:
hostnameIndex = USED_HOSTNAMES.index(hostname)
h2oPortOffset = PORTS_PER_SLOT * (executor + hostnameIndex)
h2oPort += h2oPortOffset
print "Possible h2o base_port range is %s to %s" % \
(DEFAULT_BASE_PORT, DEFAULT_BASE_PORT + (PORTS_PER_SLOT * EXECUTOR_NUM * len(USED_HOSTNAMES)) - 2)
print "Possible h2o ports used ranged is %s to %s" % \
(DEFAULT_BASE_PORT, DEFAULT_BASE_PORT + (PORTS_PER_SLOT * EXECUTOR_NUM * len(USED_HOSTNAMES)) - 1)
print "want to 'export H2O_PORT=%s'" % h2oPort
print "want to 'export H2O_PORT_OFFSET=%s # legacy'" % h2oPortOffset
f = open('H2O_BASE_PORT.sh','w')
f.write('export H2O_PORT=%s\n' % h2oPort)
f.write('export H2O_PORT_OFFSET=%s # legacy\n' % h2oPortOffset)
f.close()
print "\nNow please:\nsource ./H2O_BASE_PORT.sh"
|
Train the model asynchronously ( to block for results call: meth: join ).
|
def start(self, x, y=None, training_frame=None, offset_column=None, fold_column=None,
weights_column=None, validation_frame=None, **params):
"""
Train the model asynchronously (to block for results call :meth:`join`).
:param x: A list of column names or indices indicating the predictor columns.
:param y: An index or a column name indicating the response column.
:param H2OFrame training_frame: The H2OFrame having the columns indicated by x and y (as well as any
additional columns specified by fold, offset, and weights).
:param offset_column: The name or index of the column in training_frame that holds the offsets.
:param fold_column: The name or index of the column in training_frame that holds the per-row fold
assignments.
:param weights_column: The name or index of the column in training_frame that holds the per-row weights.
:param validation_frame: H2OFrame with validation data to be scored on while training.
"""
self._future = True
self.train(x=x,
y=y,
training_frame=training_frame,
offset_column=offset_column,
fold_column=fold_column,
weights_column=weights_column,
validation_frame=validation_frame,
**params)
|
Wait until job s completion.
|
def join(self):
"""Wait until job's completion."""
self._future = False
self._job.poll()
model_key = self._job.dest_key
self._job = None
model_json = h2o.api("GET /%d/Models/%s" % (self._rest_version, model_key))["models"][0]
self._resolve_model(model_key, model_json)
|
Train the H2O model.
|
def train(self, x=None, y=None, training_frame=None, offset_column=None, fold_column=None,
weights_column=None, validation_frame=None, max_runtime_secs=None, ignored_columns=None,
model_id=None, verbose=False):
"""
Train the H2O model.
:param x: A list of column names or indices indicating the predictor columns.
:param y: An index or a column name indicating the response column.
:param H2OFrame training_frame: The H2OFrame having the columns indicated by x and y (as well as any
additional columns specified by fold, offset, and weights).
:param offset_column: The name or index of the column in training_frame that holds the offsets.
:param fold_column: The name or index of the column in training_frame that holds the per-row fold
assignments.
:param weights_column: The name or index of the column in training_frame that holds the per-row weights.
:param validation_frame: H2OFrame with validation data to be scored on while training.
:param float max_runtime_secs: Maximum allowed runtime in seconds for model training. Use 0 to disable.
:param bool verbose: Print scoring history to stdout. Defaults to False.
"""
self._train(x=x, y=y, training_frame=training_frame, offset_column=offset_column, fold_column=fold_column,
weights_column=weights_column, validation_frame=validation_frame, max_runtime_secs=max_runtime_secs,
ignored_columns=ignored_columns, model_id=model_id, verbose=verbose)
|
Fit an H2O model as part of a scikit - learn pipeline or grid search.
|
def fit(self, X, y=None, **params):
"""
Fit an H2O model as part of a scikit-learn pipeline or grid search.
A warning will be issued if a caller other than sklearn attempts to use this method.
:param H2OFrame X: An H2OFrame consisting of the predictor variables.
:param H2OFrame y: An H2OFrame consisting of the response variable.
:param params: Extra arguments.
:returns: The current instance of H2OEstimator for method chaining.
"""
stk = inspect.stack()[1:]
warn = True
for s in stk:
mod = inspect.getmodule(s[0])
if mod:
warn = "sklearn" not in mod.__name__
if not warn: break
if warn:
warnings.warn("\n\n\t`fit` is not recommended outside of the sklearn framework. Use `train` instead.",
UserWarning, stacklevel=2)
training_frame = X.cbind(y) if y is not None else X
x = X.names
y = y.names[0] if y is not None else None
self.train(x, y, training_frame, **params)
return self
|
Obtain parameters for this estimator.
|
def get_params(self, deep=True):
"""
Obtain parameters for this estimator.
Used primarily for sklearn Pipelines and sklearn grid search.
:param deep: If True, return parameters of all sub-objects that are estimators.
:returns: A dict of parameters
"""
out = dict()
for key, value in self.parms.items():
if deep and isinstance(value, H2OEstimator):
deep_items = list(value.get_params().items())
out.update((key + "__" + k, val) for k, val in deep_items)
out[key] = value
return out
|
In order to use convert_H2OXGBoostParams_2_XGBoostParams and convert_H2OFrame_2_DMatrix you must import the following toolboxes: xgboost pandas numpy and scipy. sparse.
|
def convert_H2OXGBoostParams_2_XGBoostParams(self):
'''
In order to use convert_H2OXGBoostParams_2_XGBoostParams and convert_H2OFrame_2_DMatrix, you must import
the following toolboxes: xgboost, pandas, numpy and scipy.sparse.
Given an H2OXGBoost model, this method will generate the corresponding parameters that should be used by
native XGBoost in order to give exactly the same result, assuming that the same dataset
(derived from h2oFrame) is used to train the native XGBoost model.
Follow the steps below to compare H2OXGBoost and native XGBoost:
1. Train the H2OXGBoost model with H2OFrame trainFile and generate a prediction:
h2oModelD = H2OXGBoostEstimator(**h2oParamsD) # parameters specified as a dict()
h2oModelD.train(x=myX, y=y, training_frame=trainFile) # train with H2OFrame trainFile
h2oPredict = h2oPredictD = h2oModelD.predict(trainFile)
2. Derive the DMatrix from H2OFrame:
nativeDMatrix = trainFile.convert_H2OFrame_2_DMatrix(myX, y, h2oModelD)
3. Derive the parameters for native XGBoost:
nativeParams = h2oModelD.convert_H2OXGBoostParams_2_XGBoostParams()
4. Train your native XGBoost model and generate a prediction:
nativeModel = xgb.train(params=nativeParams[0], dtrain=nativeDMatrix, num_boost_round=nativeParams[1])
nativePredict = nativeModel.predict(data=nativeDMatrix, ntree_limit=nativeParams[1].
5. Compare the predictions h2oPredict from H2OXGBoost, nativePredict from native XGBoost.
:return: nativeParams, num_boost_round
'''
import xgboost as xgb
nativeParams = self._model_json["output"]["native_parameters"]
nativeXGBoostParams = dict()
for (a,keyname,keyvalue) in nativeParams.cell_values:
nativeXGBoostParams[keyname]=keyvalue
paramsSet = self.full_parameters
return nativeXGBoostParams, paramsSet['ntrees']['actual_value']
|
If a parameter is not stored in parms dict save it there ( even though the value is None ). Else check if the parameter has been already set during initialization of estimator. If yes check the new value is the same or not. If the values are different set the last passed value to params dict and throw UserWarning.
|
def _check_and_save_parm(self, parms, parameter_name, parameter_value):
"""
If a parameter is not stored in parms dict save it there (even though the value is None).
Else check if the parameter has been already set during initialization of estimator. If yes, check the new value is the same or not. If the values are different, set the last passed value to params dict and throw UserWarning.
"""
if parameter_name not in parms:
parms[parameter_name] = parameter_value
elif parameter_value is not None and parms[parameter_name] != parameter_value:
parms[parameter_name] = parameter_value
warnings.warn("\n\n\t`%s` parameter has been already set and had a different value in `train` method. The last passed value \"%s\" is used." % (parameter_name, parameter_value), UserWarning, stacklevel=2)
|
Return True if file_name matches a regexp for an R demo. False otherwise.: param file_name: file to test
|
def is_rdemo(file_name):
"""
Return True if file_name matches a regexp for an R demo. False otherwise.
:param file_name: file to test
"""
packaged_demos = ["h2o.anomaly.R", "h2o.deeplearning.R", "h2o.gbm.R", "h2o.glm.R", "h2o.glrm.R", "h2o.kmeans.R",
"h2o.naiveBayes.R", "h2o.prcomp.R", "h2o.randomForest.R"]
if file_name in packaged_demos: return True
if re.match("^rdemo.*\.(r|R|ipynb)$", file_name): return True
return False
|
Return True if file_name matches a regexp for an ipython notebook. False otherwise.: param file_name: file to test
|
def is_ipython_notebook(file_name):
"""
Return True if file_name matches a regexp for an ipython notebook. False otherwise.
:param file_name: file to test
"""
if (not re.match("^.*checkpoint\.ipynb$", file_name)) and re.match("^.*\.ipynb$", file_name): return True
return False
|
scan through the java output text and extract the java messages related to running test specified in curr_testname. Parameters ----------: param node_list: list of H2O nodes List of H2o nodes associated with an H2OCloud ( cluster ) that are performing the test specified in curr_testname.: param curr_testname: str Store the unit test name ( can be R unit or Py unit ) that has been completed and failed.: return: a string object that is either empty or the java messages that associated with the test in curr_testname. The java messages can usually be found in one of the java_ * _0. out. txt
|
def grab_java_message(node_list, curr_testname):
"""scan through the java output text and extract the java messages related to running
test specified in curr_testname.
Parameters
----------
:param node_list: list of H2O nodes
List of H2o nodes associated with an H2OCloud (cluster) that are performing the test specified in curr_testname.
:param curr_testname: str
Store the unit test name (can be R unit or Py unit) that has been completed and failed.
:return: a string object that is either empty or the java messages that associated with the test in curr_testname.
The java messages can usually be found in one of the java_*_0.out.txt
"""
global g_java_start_text # contains text that describe the start of a unit test.
java_messages = ""
start_test = False # denote when the current test was found in the java_*_0.out.txt file
# grab each java file and try to grab the java messages associated with curr_testname
for each_node in node_list:
java_filename = each_node.output_file_name # find the java_*_0.out.txt file
if os.path.isfile(java_filename):
java_file = open(java_filename, 'r')
for each_line in java_file:
if g_java_start_text in each_line:
start_str, found, end_str = each_line.partition(g_java_start_text)
if len(found) > 0: # a new test is being started.
current_testname = end_str.strip() # grab the test name and check if it is curr_testname
if current_testname == curr_testname:
# found the line starting with current test. Grab everything now
start_test = True # found text in java_*_0.out.txt that describe curr_testname
# add header to make JAVA messages visible.
java_messages += "\n\n**********************************************************\n"
java_messages += "**********************************************************\n"
java_messages += "JAVA Messages\n"
java_messages += "**********************************************************\n"
java_messages += "**********************************************************\n\n"
else:
# found a differnt test than our curr_testname. We are done!
if start_test:
# in the middle of curr_testname but found a new test starting, can quit now.
break
# store java message associated with curr_testname into java_messages
if start_test:
java_messages += each_line
java_file.close() # finished finding java messages
if start_test:
# found java message associate with our test already. No need to continue the loop.
break
return java_messages
|
Helper function to handle caught signals.
|
def signal_handler(signum, stackframe):
"""Helper function to handle caught signals."""
global g_runner
global g_handling_signal
if g_handling_signal:
# Don't do this recursively.
return
g_handling_signal = True
print("")
print("----------------------------------------------------------------------")
print("")
print("SIGNAL CAUGHT (" + str(signum) + "). TEARING DOWN CLOUDS.")
print("")
print("----------------------------------------------------------------------")
g_runner.terminate()
|
Print USAGE help.
|
def usage():
"""
Print USAGE help.
"""
print("")
print("Usage: " + g_script_name + " [...options...]")
print("")
print(" (Output dir is: " + str(g_output_dir) + ")")
print(" (Default number of clouds is: " + str(g_num_clouds) + ")")
print("")
print(" --wipeall Remove all prior test state before starting, particularly")
print(" random seeds.")
print(" (Removes master_seed file and all Rsandbox directories.")
print(" Also wipes the output dir before starting.)")
print("")
print(" --wipe Wipes the output dir before starting. Keeps old random seeds.")
print("")
print(" --baseport The first port at which H2O starts searching for free ports.")
print("")
print(" --numclouds The number of clusters to start.")
print(" Each test is randomly assigned to a cluster.")
print("")
print(" --numnodes The number of nodes in the cluster.")
print(" When this is specified, numclouds must be 1.")
print("")
print(" --test If you only want to run one test, specify it like this.")
print("")
print(" --testlist A file containing a list of tests to run (for example the")
print(" 'failed.txt' file from the output directory).")
print(" --excludelist A file containing a list of tests to NOT run.")
print("")
print(" --testgroup Test a group of tests by function:")
print(" pca, glm, kmeans, gbm, rf, deeplearning, algos, golden, munging, parser")
print("")
print(" --testsize Sizes (and by extension length) of tests to run:")
print(" s=small (seconds), m=medium (a minute or two), l=large (longer), x=xlarge (very big)")
print(" (Default is to run all tests.)")
print("")
print(" --usecloud ip:port of cluster to send tests to instead of starting clusters.")
print(" (When this is specified, numclouds is ignored.)")
print("")
print(" --usecloud2 cloud.cfg: Use a set clusters defined in cloud.config to run tests on.")
print(" (When this is specified, numclouds, numnodes, and usecloud are ignored.)")
print("")
print(" --client Send REST API commands through client mode.")
print("")
print(" --norun Perform side effects like wipe, but don't actually run tests.")
print("")
print(" --jvm.xmx Configure size of launched JVM running H2O. E.g. '--jvm.xmx 3g'")
print("")
print(" --jvm.cp Classpath argument, in addition to h2o.jar path. E.g. "
"'--jvm.cp /Users/h2o/mysql-connector-java-5.1.38-bin.jar'")
print("")
print(" --nopass Run the NOPASS and NOFEATURE tests only and do not ignore any failures.")
print("")
print(" --nointernal Don't run the INTERNAL tests.")
print("")
print(" --c Start the JVMs in a convenient location.")
print("")
print(" --h2ojar Supply a path to the H2O jar file.")
print("")
print(" --tar Supply a path to the R TAR.")
print("")
print("")
print(" --pto The phantomjs timeout in seconds. Default is 3600 (1hr).")
print("")
print(" --noxunit Do not produce xUnit reports.")
print("")
print(" --rPkgVerChk Check that Jenkins-approved R packages/versions are present")
print("")
print(" --onHadoop Indication that tests will be run on h2o multinode hadoop clusters.")
print(" `locate` and `sandbox` runit/pyunit test utilities use this indication in order to")
print(" behave properly. --hadoopNamenode must be specified if --onHadoop option is used.")
print(" --hadoopNamenode Specifies that the runit/pyunit tests have access to this hadoop namenode.")
print(" runit/pyunit test utilities have ability to retrieve this value.")
print("")
print(" --perf Save Jenkins build id, date, machine ip, git hash, name, start time, finish time,")
print(" pass, ncpus, os, and job name of each test to perf.csv in the results directory.")
print(" Takes three parameters: git hash, git branch, and build id, job name in that order.")
print("")
print(" --jacoco Generate code coverage data using JaCoCo. Class includes and excludes may optionally")
print(" follow in the format of [includes]:[excludes] where [...] denotes a list of")
print(" classes, each separated by a comma (,). Wildcard characters (* and ?) may be used.")
print("")
print(" --geterrs Generate xml file that contains the actual unit test errors and the actual Java error.")
print("")
print(" --test.ssl Runs all the nodes with SSL enabled.")
print("")
print(" --ldap.username Username for LDAP.")
print("")
print(" --ldap.password Password for LDAP.")
print("")
print(" --ldap.config Path to LDAP config. If set, all nodes will be started with LDAP support.")
print("")
print(" --kerb.principal Kerberos service principal.")
print("")
print(" --jvm.opts Additional JVM options.")
print("")
print(" --restLog If set, enable REST API logging. Logs will be available at <resultsDir>/rest.log.")
print(" Please note, that enablig REST API logging will increase the execution time and that")
print(" the log file might be large (> 2GB).")
print(" If neither --test nor --testlist is specified, then the list of tests is")
print(" discovered automatically as files matching '*runit*.R'.")
print("")
print("")
print("Examples:")
print("")
print(" Just accept the defaults and go (note: output dir must not exist):")
print(" " + g_script_name)
print("")
print(" Remove all random seeds (i.e. make new ones) but don't run any tests:")
print(" " + g_script_name + " --wipeall --norun")
print("")
print(" For a powerful laptop with 8 cores (keep default numclouds):")
print(" " + g_script_name + " --wipeall")
print("")
print(" For a big server with 32 cores:")
print(" " + g_script_name + " --wipeall --numclouds 16")
print("")
print(" Just run the tests that finish quickly")
print(" " + g_script_name + " --wipeall --testsize s")
print("")
print(" Run one specific test, keeping old random seeds:")
print(" " + g_script_name + " --wipe --test path/to/test.R")
print("")
print(" Rerunning failures from a previous run, keeping old random seeds:")
print(" # Copy failures.txt, otherwise --wipe removes the directory with the list!")
print(" cp " + os.path.join(g_output_dir, "failures.txt") + " .")
print(" " + g_script_name + " --wipe --numclouds 16 --testlist failed.txt")
print("")
print(" Run tests on a pre-existing cloud (e.g. in a debugger), keeping old random seeds:")
print(" " + g_script_name + " --wipe --usecloud ip:port")
print("")
print(" Run tests with JaCoCo enabled, excluding org.example1 and org.example2")
print(" " + g_script_name + " --jacoco :org.example1,org.example2")
sys.exit(1)
|
Parse the arguments into globals ( ain t this an ugly duckling? ).
|
def parse_args(argv):
"""
Parse the arguments into globals (ain't this an ugly duckling?).
TODO: replace this machinery with argparse module.
"""
global g_base_port
global g_num_clouds
global g_nodes_per_cloud
global g_wipe_test_state
global g_wipe_output_dir
global g_test_to_run
global g_test_list_file
global g_exclude_list_file
global g_test_group
global g_run_small
global g_run_medium
global g_run_large
global g_run_xlarge
global g_use_cloud
global g_use_cloud2
global g_use_client
global g_config
global g_use_proto
global g_use_ip
global g_use_port
global g_no_run
global g_jvm_xmx
global g_jvm_cp
global g_nopass
global g_nointernal
global g_convenient
global g_path_to_h2o_jar
global g_path_to_tar
global g_path_to_whl
global g_jacoco_include
global g_jacoco_options
global g_produce_unit_reports
global g_phantomjs_to
global g_phantomjs_packs
global g_r_pkg_ver_chk
global g_on_hadoop
global g_hadoop_namenode
global g_r_test_setup
global g_py_test_setup
global g_perf
global g_git_hash
global g_git_branch
global g_machine_ip
global g_date
global g_build_id
global g_ncpu
global g_os
global g_job_name
global g_py3
global g_pycoverage
global g_use_xml2
global g_test_ssl
global g_ldap_username
global g_ldap_password
global g_kerb_principal
global g_ldap_config
global g_rest_log
global g_jvm_opts
i = 1
while i < len(argv):
s = argv[i]
if s == "--baseport":
i += 1
if i >= len(argv):
usage()
g_base_port = int(argv[i])
elif s == "--py3":
g_py3 = True
elif s == "--coverage":
g_pycoverage = True
elif s == "--numclouds":
i += 1
if i >= len(argv):
usage()
g_num_clouds = int(argv[i])
elif s == "--numnodes":
i += 1
if i >= len(argv):
usage()
g_nodes_per_cloud = int(argv[i])
elif s == "--wipeall":
g_wipe_test_state = True
g_wipe_output_dir = True
elif s == "--wipe":
g_wipe_output_dir = True
elif s == "--test":
i += 1
if i >= len(argv):
usage()
g_test_to_run = TestRunner.find_test(argv[i])
elif s == "--testlist":
i += 1
if i >= len(argv):
usage()
g_test_list_file = argv[i]
elif s == "--excludelist":
i += 1
if i >= len(argv):
usage()
g_exclude_list_file = argv[i]
elif s == "--testgroup":
i += 1
if i >= len(argv):
usage()
g_test_group = argv[i]
elif s == "--testsize":
i += 1
if i >= len(argv):
usage()
v = argv[i]
if re.match(r'(s)?(m)?(l)?', v):
if 's' not in v:
g_run_small = False
if 'm' not in v:
g_run_medium = False
if 'l' not in v:
g_run_large = False
if 'x' not in v:
g_run_xlarge = False
else:
bad_arg(s)
elif s == "--usecloud":
i += 1
if i >= len(argv):
usage()
s = argv[i]
proto = ""
if s.lower().startswith("https://"):
proto = "https://"
s = s[8:]
m = re.match(r'(\S+):([1-9][0-9]*)', s)
if m is None:
unknown_arg(s)
g_use_cloud = True
g_use_proto = proto
g_use_ip = m.group(1)
port_string = m.group(2)
g_use_port = int(port_string)
elif s == "--usecloud2":
i += 1
if i >= len(argv):
usage()
s = argv[i]
if s is None:
unknown_arg(s)
g_use_cloud2 = True
g_config = s
elif s == "--client":
g_use_client = True
elif s == "--nopass":
g_nopass = True
elif s == "--nointernal":
g_nointernal = True
elif s == "--c":
g_convenient = True
elif s == "--h2ojar":
i += 1
g_path_to_h2o_jar = os.path.abspath(argv[i])
elif s == "--pto":
i += 1
g_phantomjs_to = int(argv[i])
elif s == "--ptt":
i += 1
g_phantomjs_packs = argv[i]
elif s == "--tar":
i += 1
g_path_to_tar = os.path.abspath(argv[i])
elif s == "--whl":
i += 1
g_path_to_whl = os.path.abspath(argv[i])
elif s == "--jvm.xmx":
i += 1
if i >= len(argv):
usage()
g_jvm_xmx = argv[i]
elif s == "--jvm.cp":
i += 1
if i > len(argv):
usage()
g_jvm_cp = argv[i]
elif s == "--norun":
g_no_run = True
elif s == "--noxunit":
g_produce_unit_reports = False
elif s == "--jacoco":
g_jacoco_include = True
if i + 1 < len(argv):
s = argv[i + 1]
m = re.match(r'(?P<includes>([^:,]+(,[^:,]+)*)?):(?P<excludes>([^:,]+(,[^:,]+)*)?)$', s)
if m is not None:
g_jacoco_options[0] = m.group("includes")
g_jacoco_options[1] = m.group("excludes")
elif s == "-h" or s == "--h" or s == "-help" or s == "--help":
usage()
elif s == "--rPkgVerChk":
g_r_pkg_ver_chk = True
elif s == "--onHadoop":
g_on_hadoop = True
elif s == "--hadoopNamenode":
i += 1
if i >= len(argv):
usage()
g_hadoop_namenode = argv[i]
elif s == "--perf":
g_perf = True
i += 1
if i >= len(argv):
usage()
g_git_hash = argv[i]
i += 1
if i >= len(argv):
usage()
g_git_branch = argv[i]
i += 1
if i >= len(argv):
usage()
g_build_id = argv[i]
i += 1
if i >= len(argv):
usage()
g_job_name = argv[i]
elif s == "--geterrs":
g_use_xml2 = True
elif s == "--test_ssl":
g_test_ssl = True
elif s == '--ldap.config':
i += 1
if i >= len(argv):
usage()
g_ldap_config = argv[i]
elif s == '--ldap.username':
i += 1
if i >= len(argv):
usage()
g_ldap_username = argv[i]
elif s == '--ldap.password':
i += 1
if i >= len(argv):
usage()
g_ldap_password = argv[i]
elif s == '--kerb.principal':
i += 1
if i >= len(argv):
usage()
g_kerb_principal = argv[i]
elif s == '--jvm.opts':
i += 1
if i >= len(argv):
usage()
g_jvm_opts = argv[i]
elif s == '--restLog':
g_rest_log = True
else:
unknown_arg(s)
i += 1
if int(g_use_client) + int(g_use_cloud) + int(g_use_cloud2) > 1:
print("")
print("ERROR: --client, --usecloud and --usecloud2 are mutually exclusive.")
print("")
sys.exit(1)
|
Clear the output directory.
|
def wipe_output_dir():
"""Clear the output directory."""
print("Wiping output directory.")
try:
if os.path.exists(g_output_dir):
shutil.rmtree(str(g_output_dir))
except OSError as e:
print("ERROR: Removing output directory %s failed: " % g_output_dir)
print(" (errno {0}): {1}".format(e.errno, e.strerror))
print("")
sys.exit(1)
|
This function is written to remove sandbox directories if they exist under the parent_dir.
|
def remove_sandbox(parent_dir, dir_name):
"""
This function is written to remove sandbox directories if they exist under the
parent_dir.
:param parent_dir: string denoting full parent directory path
:param dir_name: string denoting directory path which could be a sandbox
:return: None
"""
if "Rsandbox" in dir_name:
rsandbox_dir = os.path.join(parent_dir, dir_name)
try:
if sys.platform == "win32":
os.system(r'C:/cygwin64/bin/rm.exe -r -f "{0}"'.format(rsandbox_dir))
else:
shutil.rmtree(rsandbox_dir)
except OSError as e:
print("")
print("ERROR: Removing RSandbox directory failed: " + rsandbox_dir)
print(" (errno {0}): {1}".format(e.errno, e.strerror))
print("")
sys.exit(1)
|
Main program.: param argv Command - line arguments: return none
|
def main(argv):
"""
Main program.
:param argv Command-line arguments
:return none
"""
global g_script_name
global g_num_clouds
global g_nodes_per_cloud
global g_output_dir
global g_test_to_run
global g_test_list_file
global g_exclude_list_file
global g_test_group
global g_runner
global g_nopass
global g_nointernal
global g_path_to_tar
global g_path_to_whl
global g_perf
global g_git_hash
global g_git_branch
global g_machine_ip
global g_date
global g_build_id
global g_ncpu
global g_os
global g_job_name
global g_test_ssl
g_script_name = os.path.basename(argv[0])
# Calculate test_root_dir.
test_root_dir = os.path.realpath(os.getcwd())
# Calculate global variables.
g_output_dir = os.path.join(test_root_dir, str("results"))
g_failed_output_dir = os.path.join(g_output_dir, str("failed"))
testreport_dir = os.path.join(test_root_dir, str("../build/test-results"))
# Override any defaults with the user's choices.
parse_args(argv)
# Look for h2o jar file.
h2o_jar = g_path_to_h2o_jar
if h2o_jar is None:
possible_h2o_jar_parent_dir = test_root_dir
while True:
possible_h2o_jar_dir = os.path.join(possible_h2o_jar_parent_dir, "build")
possible_h2o_jar = os.path.join(possible_h2o_jar_dir, "h2o.jar")
if os.path.exists(possible_h2o_jar):
h2o_jar = possible_h2o_jar
break
next_possible_h2o_jar_parent_dir = os.path.dirname(possible_h2o_jar_parent_dir)
if next_possible_h2o_jar_parent_dir == possible_h2o_jar_parent_dir:
break
possible_h2o_jar_parent_dir = next_possible_h2o_jar_parent_dir
# Wipe output directory if requested.
if g_wipe_output_dir:
wipe_output_dir()
# Wipe persistent test state if requested.
if g_wipe_test_state:
wipe_test_state(test_root_dir)
# Create runner object.
# Just create one cloud if we're only running one test, even if the user specified more.
if g_test_to_run is not None:
g_num_clouds = 1
g_runner = TestRunner(test_root_dir,
g_use_cloud, g_use_cloud2, g_use_client, g_config, g_use_ip, g_use_port,
g_num_clouds, g_nodes_per_cloud, h2o_jar, g_base_port, g_jvm_xmx, g_jvm_cp,
g_output_dir, g_failed_output_dir, g_path_to_tar, g_path_to_whl, g_produce_unit_reports,
testreport_dir, g_r_pkg_ver_chk, g_hadoop_namenode, g_on_hadoop, g_perf, g_test_ssl,
g_ldap_config, g_jvm_opts)
# Build test list.
if g_exclude_list_file is not None:
g_runner.read_exclude_list_file(g_exclude_list_file)
if g_test_to_run is not None:
g_runner.add_test(g_test_to_run)
elif g_test_list_file is not None:
g_runner.read_test_list_file(g_test_list_file)
else:
# Test group can be None or not.
g_runner.build_test_list(g_test_group, g_run_small, g_run_medium, g_run_large, g_run_xlarge, g_nopass,
g_nointernal)
# If no run is specified, then do an early exit here.
if g_no_run:
sys.exit(0)
# Handle killing the runner.
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
# Sanity check existence of H2O jar file before starting the cloud.
if not (h2o_jar and os.path.exists(h2o_jar)):
print("")
print("ERROR: H2O jar not found")
print("")
sys.exit(1)
# Run.
try:
g_runner.start_clouds()
g_runner.run_tests(g_nopass)
finally:
g_runner.check_clouds()
g_runner.stop_clouds()
g_runner.report_summary(g_nopass)
# If the overall regression did not pass then exit with a failure status code.
if not g_runner.get_regression_passed():
sys.exit(1)
|
Start one node of H2O. ( Stash away the self. child and self. pid internally here. )
|
def start(self):
"""
Start one node of H2O.
(Stash away the self.child and self.pid internally here.)
:return none
"""
# there is no hdfs currently in ec2, except s3n/hdfs
# the core-site.xml provides s3n info
# it's possible that we can just always hardware the hdfs version
# to match the cdh3 cluster we're hard-wiring tests to
# i.e. it won't make s3n/s3 break on ec2
if self.is_client:
main_class = "water.H2OClientApp"
else:
main_class = "water.H2OApp"
if "JAVA_HOME" in os.environ:
java = os.environ["JAVA_HOME"] + "/bin/java"
else:
java = "java"
classpath_sep = ";" if sys.platform == "win32" else ":"
classpath = self.h2o_jar if self.cp == "" else self.h2o_jar + classpath_sep + self.cp
cmd = [java,
# "-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005",
"-Xmx" + self.xmx,
"-ea"]
if self.jvm_opts is not None:
cmd += [self.jvm_opts]
cmd += ["-cp", classpath,
main_class,
"-name", self.cloud_name,
"-port", str(self.port),
"-ip", self.ip]
if self.flatfile is not None:
cmd += ["-flatfile", self.flatfile]
if self.ldap_config_path is not None:
cmd.append('-login_conf')
cmd.append(self.ldap_config_path)
cmd.append('-ldap_login')
# If the jacoco flag was included, then modify cmd to generate coverage
# data using the jacoco agent
if g_jacoco_include:
root_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
agent_dir = os.path.join(root_dir, "jacoco", "jacocoagent.jar")
jresults_dir = os.path.join(self.output_dir, "jacoco")
if not os.path.exists(jresults_dir):
os.mkdir(jresults_dir)
jresults_dir = os.path.join(jresults_dir, "{cloud}_{node}".format(cloud=self.cloud_num, node=self.node_num))
jacoco = "-javaagent:" + agent_dir + "=destfile=" + \
os.path.join(jresults_dir, "{cloud}_{node}.exec".format(cloud=self.cloud_num, node=self.node_num))
opt0, opt1 = g_jacoco_options
if opt0 is not None:
jacoco += ",includes={inc}".format(inc=opt0.replace(',', ':'))
if opt1 is not None:
jacoco += ",excludes={ex}".format(ex=opt1.replace(',', ':'))
cmd = cmd[:1] + [jacoco] + cmd[1:]
if self.test_ssl:
cmd.append("-internal_security_conf")
if g_convenient:
cmd.append("../h2o-algos/src/test/resources/ssl.properties")
else:
cmd.append("../../../h2o-algos/src/test/resources/ssl3.properties")
# Add S3N credentials to cmd if they exist.
# ec2_hdfs_config_file_name = os.path.expanduser("~/.ec2/core-site.xml")
# if (os.path.exists(ec2_hdfs_config_file_name)):
# cmd.append("-hdfs_config")
# cmd.append(ec2_hdfs_config_file_name)
self.output_file_name = \
os.path.join(self.output_dir, "java_" + str(self.cloud_num) + "_" + str(self.node_num) + ".out.txt")
f = open(self.output_file_name, "w")
if g_convenient:
cwd = os.getcwd()
here = os.path.abspath(os.path.dirname(__file__))
there = os.path.abspath(os.path.join(here, ".."))
os.chdir(there)
self.child = subprocess.Popen(args=cmd,
stdout=f,
stderr=subprocess.STDOUT,
cwd=there)
os.chdir(cwd)
else:
try:
self.child = subprocess.Popen(args=cmd,
stdout=f,
stderr=subprocess.STDOUT,
cwd=self.output_dir)
self.pid = self.child.pid
print("+ CMD: " + ' '.join(cmd))
except OSError:
raise "Failed to spawn %s in %s" % (cmd, self.output_dir)
|
Look at the stdout log and figure out which port the JVM chose.
|
def scrape_port_from_stdout(self):
"""
Look at the stdout log and figure out which port the JVM chose.
If successful, port number is stored in self.port; otherwise the
program is terminated. This call is blocking, and will wait for
up to 30s for the server to start up.
"""
regex = re.compile(r"Open H2O Flow in your web browser: https?://([^:]+):(\d+)")
retries_left = 30
while retries_left and not self.terminated:
with open(self.output_file_name, "r") as f:
for line in f:
mm = re.search(regex, line)
if mm is not None:
self.port = mm.group(2)
print("H2O cloud %d node %d listening on port %s\n with output file %s" %
(self.cloud_num, self.node_num, self.port, self.output_file_name))
return
if self.terminated: break
retries_left -= 1
time.sleep(1)
if self.terminated: return
print("\nERROR: Too many retries starting cloud %d.\nCheck the output log %s.\n" %
(self.cloud_num, self.output_file_name))
sys.exit(1)
|
Look at the stdout log and wait until the cluster of proper size is formed. This call is blocking. Exit if this fails.
|
def scrape_cloudsize_from_stdout(self, nodes_per_cloud):
"""
Look at the stdout log and wait until the cluster of proper size is formed.
This call is blocking.
Exit if this fails.
:param nodes_per_cloud:
:return none
"""
retries = 60
while retries > 0:
if self.terminated: return
f = open(self.output_file_name, "r")
s = f.readline()
while len(s) > 0:
if self.terminated: return
match_groups = re.search(r"Cloud of size (\d+) formed", s)
if match_groups is not None:
size = match_groups.group(1)
if size is not None:
size = int(size)
if size == nodes_per_cloud:
f.close()
return
s = f.readline()
f.close()
retries -= 1
if self.terminated: return
time.sleep(1)
print("")
print("ERROR: Too many retries starting cloud.")
print("")
sys.exit(1)
|
Normal node shutdown. Ignore failures for now.
|
def stop(self):
"""
Normal node shutdown.
Ignore failures for now.
:return none
"""
if self.pid > 0:
print("Killing JVM with PID {}".format(self.pid))
try:
self.child.terminate()
self.child.wait()
except OSError:
pass
self.pid = -1
|
Start H2O cluster. The cluster is not up until wait_for_cloud_to_be_up () is called and returns.
|
def start(self):
"""
Start H2O cluster.
The cluster is not up until wait_for_cloud_to_be_up() is called and returns.
:return none
"""
for node in self.nodes:
node.start()
for node in self.client_nodes:
node.start()
|
Normal cluster shutdown.
|
def stop(self):
"""
Normal cluster shutdown.
:return none
"""
for node in self.nodes:
node.stop()
for node in self.client_nodes:
node.stop()
|
Terminate a running cluster. ( Due to a signal. )
|
def terminate(self):
"""
Terminate a running cluster. (Due to a signal.)
:return none
"""
for node in self.client_nodes:
node.terminate()
for node in self.nodes:
node.terminate()
|
Return an ip to use to talk to this cluster.
|
def get_ip(self):
""" Return an ip to use to talk to this cluster. """
if len(self.client_nodes) > 0:
node = self.client_nodes[0]
else:
node = self.nodes[0]
return node.get_ip()
|
Return a port to use to talk to this cluster.
|
def get_port(self):
""" Return a port to use to talk to this cluster. """
if len(self.client_nodes) > 0:
node = self.client_nodes[0]
else:
node = self.nodes[0]
return node.get_port()
|
This function will grab one log file from Jenkins and save it to local user directory: param g_jenkins_url:: param build_index:: param airline_java:: param airline_java_tail:: return:
|
def get_file_out(build_index, python_name, jenkin_name):
"""
This function will grab one log file from Jenkins and save it to local user directory
:param g_jenkins_url:
:param build_index:
:param airline_java:
:param airline_java_tail:
:return:
"""
global g_log_base_dir
global g_jenkins_url
global g_log_base_dir
directoryB = g_log_base_dir+'/Build'+str(build_index)
if not(os.path.isdir(directoryB)): # make directory if it does not exist
os.mkdir(directoryB)
url_string_full = g_jenkins_url+'/'+str(build_index)+jenkin_name
filename = os.path.join(directoryB, python_name)
full_command = 'curl ' + url_string_full + ' > ' + filename
subprocess.call(full_command,shell=True)
|
Main program.
|
def main(argv):
"""
Main program.
@return: none
"""
global g_log_base_dir
global g_airline_java
global g_milsongs_java
global g_airline_python
global g_milsongs_python
global g_jenkins_url
global g_airline_py_tail
global g_milsongs_py_tail
global g_airline_java_tail
global g_milsongs_java_tail
if len(argv) < 9:
print "python grabGLRMrunLogs logsBaseDirectory airlineJavaFileNameWithPath milsongJavaFileNameWithPath " \
"airlinePyunitWithPath airlinePyunitWithPath jenkinsJobURL startBuild# endBuild#.\n"
sys.exit(1)
else: # we may be in business
# g_script_name = os.path.basename(argv[0]) # get name of script being run.
# base directory where all logs will be collected according to build #
g_log_base_dir = argv[1]
g_jenkins_url = argv[2]
g_airline_java = argv[3]
g_milsongs_java = argv[4]
g_airline_python = argv[5]
g_milsongs_python = argv[6]
start_number = int(argv[7])
end_number = int(argv[8])
if (start_number > end_number):
print "startBuild# must be <= end_number"
sys.exit(1)
else:
for build_index in range(start_number, end_number+1): # grab log info for all builds
# copy the java jobs
get_file_out(build_index, g_airline_java, g_airline_java_tail)
get_file_out(build_index, g_milsongs_java, g_milsongs_java_tail)
# copy the pyunit jobs
get_file_out(build_index, g_airline_python, g_airline_py_tail)
get_file_out(build_index, g_milsongs_python, g_milsongs_py_tail)
|
Plot training set ( and validation set if available ) scoring history for an H2OBinomialModel.
|
def plot(self, timestep="AUTO", metric="AUTO", server=False, **kwargs):
"""
Plot training set (and validation set if available) scoring history for an H2OBinomialModel.
The timestep and metric arguments are restricted to what is available in its scoring history.
:param str timestep: A unit of measurement for the x-axis.
:param str metric: A unit of measurement for the y-axis.
:param bool server: if True, then generate the image inline (using matplotlib's "Agg" backend)
"""
assert_is_type(metric, "AUTO", "logloss", "auc", "classification_error", "rmse")
if self._model_json["algo"] in ("deeplearning", "deepwater", "xgboost", "drf", "gbm"):
if metric == "AUTO":
metric = "logloss"
self._plot(timestep=timestep, metric=metric, server=server)
|
Return the coordinates of the ROC curve for a given set of data.
|
def roc(self, train=False, valid=False, xval=False):
"""
Return the coordinates of the ROC curve for a given set of data.
The coordinates are two-tuples containing the false positive rates as a list and true positive rates as a list.
If all are False (default), then return is the training data. If more than one ROC
curve is requested, the data is returned as a dictionary of two-tuples.
:param bool train: If True, return the ROC value for the training data.
:param bool valid: If True, return the ROC value for the validation data.
:param bool xval: If True, return the ROC value for each of the cross-validated splits.
:returns: The ROC values for the specified key(s).
"""
tm = ModelBase._get_metrics(self, train, valid, xval)
m = {}
for k, v in viewitems(tm):
if v is not None:
m[k] = (v.fprs, v.tprs)
return list(m.values())[0] if len(m) == 1 else m
|
Retrieve the index in this metric s threshold list at which the given threshold is located.
|
def find_idx_by_threshold(self, threshold, train=False, valid=False, xval=False):
"""
Retrieve the index in this metric's threshold list at which the given threshold is located.
If all are False (default), then return the training metric value.
If more than one options is set to True, then return a dictionary of metrics where the keys are "train",
"valid", and "xval".
:param float threshold: Threshold value to search for in the threshold list.
:param bool train: If True, return the find idx by threshold value for the training data.
:param bool valid: If True, return the find idx by threshold value for the validation data.
:param bool xval: If True, return the find idx by threshold value for each of the cross-validated splits.
:returns: The find idx by threshold values for the specified key(s).
"""
tm = ModelBase._get_metrics(self, train, valid, xval)
m = {}
for k, v in viewitems(tm):
m[k] = None if v is None else v.find_idx_by_threshold(threshold)
return list(m.values())[0] if len(m) == 1 else m
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.