class Spinnaker(FrontEndCommonConfigurationFunctions, FrontEndCommonInterfaceFunctions, FrontEndCommonProvenanceFunctions, SpynnakerConfigurationFunctions): """ Spinnaker """ def __init__(self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None): FrontEndCommonConfigurationFunctions.__init__(self, host_name, graph_label) SpynnakerConfigurationFunctions.__init__(self) FrontEndCommonProvenanceFunctions.__init__(self) self._database_socket_addresses = set() self._database_interface = None self._create_database = None self._populations = list() if self._app_id is None: self._set_up_main_objects( app_id=config.getint("Machine", "appID"), execute_data_spec_report=config.getboolean( "Reports", "writeTextSpecs"), execute_partitioner_report=config.getboolean( "Reports", "writePartitionerReports"), execute_placer_report=config.getboolean( "Reports", "writePlacerReports"), execute_router_dat_based_report=config.getboolean( "Reports", "writeRouterDatReport"), reports_are_enabled=config.getboolean( "Reports", "reportsEnabled"), generate_performance_measurements=config.getboolean( "Reports", "outputTimesForSections"), execute_router_report=config.getboolean( "Reports", "writeRouterReports"), execute_write_reload_steps=config.getboolean( "Reports", "writeReloadSteps"), generate_transciever_report=config.getboolean( "Reports", "writeTransceiverReport"), execute_routing_info_report=config.getboolean( "Reports", "writeRouterInfoReport"), in_debug_mode=config.get("Mode", "mode") == "Debug", generate_tag_report=config.getboolean( "Reports", "writeTagAllocationReports")) self._set_up_pacman_algorthms_listings( partitioner_algorithm=config.get("Partitioner", "algorithm"), placer_algorithm=config.get("Placer", "algorithm"), key_allocator_algorithm=config.get( "KeyAllocator", "algorithm"), routing_algorithm=config.get("Routing", "algorithm")) # set up exeuctable specifics self._set_up_executable_specifics() self._set_up_report_specifics( default_report_file_path=config.get( "Reports", "defaultReportFilePath"), max_reports_kept=config.getint("Reports", "max_reports_kept"), reports_are_enabled=config.getboolean( "Reports", "reportsEnabled"), write_provance_data=config.getboolean( "Reports", "writeProvanceData"), write_text_specs=config.getboolean( "Reports", "writeTextSpecs")) self._set_up_output_application_data_specifics( max_application_binaries_kept=config.getint( "Reports", "max_application_binaries_kept"), where_to_write_application_data_files=config.get( "Reports", "defaultApplicationDataFilePath")) # set up spynnaker specifics, such as setting the machineName from conf self._set_up_machine_specifics( timestep, min_delay, max_delay, host_name) self._spikes_per_second = float(config.getfloat( "Simulation", "spikes_per_second")) self._ring_buffer_sigma = float(config.getfloat( "Simulation", "ring_buffer_sigma")) # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) FrontEndCommonInterfaceFunctions.__init__( self, self._reports_states, self._report_default_directory, self._app_data_runtime_folder) logger.info("Setting time scale factor to {}." .format(self._time_scale_factor)) logger.info("Setting appID to %d." % self._app_id) # get the machine time step logger.info("Setting machine time step to {} micro-seconds." .format(self._machine_time_step)) self._edge_count = 0 # Manager of buffered sending self._send_buffer_manager = None def run(self, run_time): """ :param run_time: :return: """ # sort out config param to be valid types width = config.get("Machine", "width") height = config.get("Machine", "height") if width == "None": width = None else: width = int(width) if height == "None": height = None else: height = int(height) number_of_boards = config.get("Machine", "number_of_boards") if number_of_boards == "None": number_of_boards = None self.setup_interfaces( hostname=self._hostname, bmp_details=config.get("Machine", "bmp_names"), downed_chips=config.get("Machine", "down_chips"), downed_cores=config.get("Machine", "down_cores"), board_version=config.getint("Machine", "version"), number_of_boards=number_of_boards, width=width, height=height, is_virtual=config.getboolean("Machine", "virtual_board"), virtual_has_wrap_arounds=config.getboolean( "Machine", "requires_wrap_arounds"), auto_detect_bmp=config.getboolean("Machine", "auto_detect_bmp")) # adds extra stuff needed by the reload script which cannot be given # directly. if self._reports_states.transciever_report: self._reload_script.runtime = run_time self._reload_script.time_scale_factor = self._time_scale_factor # create network report if needed if self._reports_states is not None: reports.network_specification_partitionable_report( self._report_default_directory, self._partitionable_graph, self._hostname) # calculate number of machine time steps if run_time is not None: self._no_machine_time_steps =\ int((run_time * 1000.0) / self._machine_time_step) ceiled_machine_time_steps = \ math.ceil((run_time * 1000.0) / self._machine_time_step) if self._no_machine_time_steps != ceiled_machine_time_steps: raise common_exceptions.ConfigurationException( "The runtime and machine time step combination result in " "a factional number of machine runable time steps and " "therefore spinnaker cannot determine how many to run for") for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractDataSpecableVertex): vertex.set_no_machine_time_steps( self._no_machine_time_steps) else: self._no_machine_time_steps = None logger.warn("You have set a runtime that will never end, this may" "cause the neural models to fail to partition " "correctly") for vertex in self._partitionable_graph.vertices: if (isinstance(vertex, AbstractPopulationRecordableVertex) and vertex.record): raise common_exceptions.ConfigurationException( "recording a population when set to infinite runtime " "is not currently supportable in this tool chain." "watch this space") do_timing = config.getboolean("Reports", "outputTimesForSections") if do_timing: timer = Timer() else: timer = None self.set_runtime(run_time) logger.info("*** Running Mapper *** ") if do_timing: timer.start_timing() self.map_model() if do_timing: timer.take_sample() # add database generation if requested needs_database = self._auto_detect_database(self._partitioned_graph) user_create_database = config.get("Database", "create_database") if ((user_create_database == "None" and needs_database) or user_create_database == "True"): wait_on_confirmation = config.getboolean( "Database", "wait_on_confirmation") self._database_interface = SpynnakerDataBaseInterface( self._app_data_runtime_folder, wait_on_confirmation, self._database_socket_addresses) self._database_interface.add_system_params( self._time_scale_factor, self._machine_time_step, self._runtime) self._database_interface.add_machine_objects(self._machine) self._database_interface.add_partitionable_vertices( self._partitionable_graph) self._database_interface.add_partitioned_vertices( self._partitioned_graph, self._graph_mapper, self._partitionable_graph) self._database_interface.add_placements(self._placements, self._partitioned_graph) self._database_interface.add_routing_infos( self._routing_infos, self._partitioned_graph) self._database_interface.add_routing_tables(self._router_tables) self._database_interface.add_tags(self._partitioned_graph, self._tags) execute_mapping = config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping") if execute_mapping: self._database_interface.create_neuron_to_key_mapping( graph_mapper=self._graph_mapper, partitionable_graph=self._partitionable_graph, partitioned_graph=self._partitioned_graph, routing_infos=self._routing_infos) # if using a reload script, add if that needs to wait for # confirmation if self._reports_states.transciever_report: self._reload_script.wait_on_confirmation = wait_on_confirmation for socket_address in self._database_socket_addresses: self._reload_script.add_socket_address(socket_address) self._database_interface.send_read_notification() # execute data spec generation if do_timing: timer.start_timing() logger.info("*** Generating Output *** ") logger.debug("") executable_targets = self.generate_data_specifications() if do_timing: timer.take_sample() # execute data spec execution if do_timing: timer.start_timing() processor_to_app_data_base_address = \ self.execute_data_specification_execution( config.getboolean("SpecExecution", "specExecOnHost"), self._hostname, self._placements, self._graph_mapper, write_text_specs=config.getboolean( "Reports", "writeTextSpecs"), runtime_application_data_folder=self._app_data_runtime_folder, machine=self._machine) if self._reports_states is not None: reports.write_memory_map_report(self._report_default_directory, processor_to_app_data_base_address) if do_timing: timer.take_sample() if (not isinstance(self._machine, VirtualMachine) and config.getboolean("Execute", "run_simulation")): if do_timing: timer.start_timing() logger.info("*** Loading tags ***") self.load_tags(self._tags) if self._do_load is True: logger.info("*** Loading data ***") self._load_application_data( self._placements, self._graph_mapper, processor_to_app_data_base_address, self._hostname, app_data_folder=self._app_data_runtime_folder, verify=config.getboolean("Mode", "verify_writes")) self.load_routing_tables(self._router_tables, self._app_id) logger.info("*** Loading executables ***") self.load_executable_images(executable_targets, self._app_id) logger.info("*** Loading buffers ***") self.set_up_send_buffering(self._partitioned_graph, self._placements, self._tags) # end of entire loading setup if do_timing: timer.take_sample() if self._do_run is True: logger.info("*** Running simulation... *** ") if do_timing: timer.start_timing() # every thing is in sync0. load the initial buffers self._send_buffer_manager.load_initial_buffers() if do_timing: timer.take_sample() wait_on_confirmation = config.getboolean( "Database", "wait_on_confirmation") send_start_notification = config.getboolean( "Database", "send_start_notification") self.wait_for_cores_to_be_ready(executable_targets, self._app_id) # wait till external app is ready for us to start if required if (self._database_interface is not None and wait_on_confirmation): self._database_interface.wait_for_confirmation() self.start_all_cores(executable_targets, self._app_id) if (self._database_interface is not None and send_start_notification): self._database_interface.send_start_notification() if self._runtime is None: logger.info("Application is set to run forever - exiting") else: self.wait_for_execution_to_complete( executable_targets, self._app_id, self._runtime, self._time_scale_factor) self._has_ran = True if self._retrieve_provance_data: progress = ProgressBar(self._placements.n_placements + 1, "getting provenance data") # retrieve provence data from central file_path = os.path.join(self._report_default_directory, "provance_data") # check the directory doesnt already exist if not os.path.exists(file_path): os.mkdir(file_path) # write provanence data self.write_provenance_data_in_xml(file_path, self._txrx) progress.update() # retrieve provenance data from any cores that provide data for placement in self._placements.placements: if isinstance(placement.subvertex, AbstractProvidesProvenanceData): core_file_path = os.path.join( file_path, "Provanence_data_for_{}_{}_{}_{}.xml".format( placement.subvertex.label, placement.x, placement.y, placement.p)) placement.subvertex.write_provenance_data_in_xml( core_file_path, self.transceiver, placement) progress.update() progress.end() elif isinstance(self._machine, VirtualMachine): logger.info( "*** Using a Virtual Machine so no simulation will occur") else: logger.info("*** No simulation requested: Stopping. ***") @property def app_id(self): """ :return: """ return self._app_id @property def has_ran(self): """ :return: """ return self._has_ran @property def machine_time_step(self): """ :return: """ return self._machine_time_step @property def no_machine_time_steps(self): """ :return: """ return self._no_machine_time_steps @property def timescale_factor(self): """ :return: """ return self._time_scale_factor @property def spikes_per_second(self): """ :return: """ return self._spikes_per_second @property def ring_buffer_sigma(self): """ :return: """ return self._ring_buffer_sigma @property def get_multi_cast_source(self): """ :return: """ return self._multi_cast_vertex @property def partitioned_graph(self): """ :return: """ return self._partitioned_graph @property def partitionable_graph(self): """ :return: """ return self._partitionable_graph @property def placements(self): """ :return: """ return self._placements @property def transceiver(self): """ :return: """ return self._txrx @property def graph_mapper(self): """ :return: """ return self._graph_mapper @property def routing_infos(self): """ :return: """ return self._routing_infos def set_app_id(self, value): """ :param value: :return: """ self._app_id = value def get_current_time(self): """ :return: """ if self._has_ran: return float(self._runtime) return 0.0 def __repr__(self): return "Spinnaker object for machine {}".format(self._hostname) def map_model(self): """ executes the pacman compilation stack """ pacman_report_state = \ self._reports_states.generate_pacman_report_states() self._add_virtual_chips() # execute partitioner self._execute_partitioner(pacman_report_state) # execute placer self._execute_placer(pacman_report_state) # exeucte tag allocator self._execute_tag_allocator(pacman_report_state) # execute pynn subedge pruning self._partitioned_graph, self._graph_mapper = \ GraphEdgeFilter(self._report_default_directory)\ .run(self._partitioned_graph, self._graph_mapper) # execute key allocator self._execute_key_allocator(pacman_report_state) # execute router self._execute_router(pacman_report_state) def _execute_tag_allocator(self, pacman_report_state): """ :param pacman_report_state: :return: """ if self._tag_allocator_algorithm is None: self._tag_allocator_algorithm = BasicTagAllocator() else: self._tag_allocator_algorithm = self._tag_allocator_algorithm() # execute tag allocation self._tags = self._tag_allocator_algorithm.allocate_tags( self._machine, self._placements) # generate reports if (pacman_report_state is not None and pacman_report_state.tag_allocation_report): pacman_reports.tag_allocator_report( self._report_default_directory, self._tags) def _execute_key_allocator(self, pacman_report_state): """ executes the key allocator :param pacman_report_state: :return: """ if self._key_allocator_algorithm is None: self._key_allocator_algorithm = BasicRoutingInfoAllocator() else: self._key_allocator_algorithm = self._key_allocator_algorithm() # execute routing info generator # Generate an n_keys map for the graph and add constraints n_keys_map = DictBasedPartitionedEdgeNKeysMap() for edge in self._partitioned_graph.subedges: vertex_slice = self._graph_mapper.get_subvertex_slice( edge.pre_subvertex) super_edge = (self._graph_mapper .get_partitionable_edge_from_partitioned_edge(edge)) if not isinstance(super_edge.pre_vertex, AbstractProvidesNKeysForEdge): n_keys_map.set_n_keys_for_patitioned_edge(edge, vertex_slice.n_atoms) else: n_keys_map.set_n_keys_for_patitioned_edge( edge, super_edge.pre_vertex.get_n_keys_for_partitioned_edge( edge, self._graph_mapper)) if isinstance(super_edge.pre_vertex, AbstractProvidesOutgoingEdgeConstraints): edge.add_constraints( super_edge.pre_vertex.get_outgoing_edge_constraints( edge, self._graph_mapper)) if isinstance(super_edge.post_vertex, AbstractProvidesIncomingEdgeConstraints): edge.add_constraints( super_edge.post_vertex.get_incoming_edge_constraints( edge, self._graph_mapper)) # execute routing info generator self._routing_infos = \ self._key_allocator_algorithm.allocate_routing_info( self._partitioned_graph, self._placements, n_keys_map) # generate reports if (pacman_report_state is not None and pacman_report_state.routing_info_report): pacman_reports.routing_info_reports( self._report_default_directory, self._partitioned_graph, self._routing_infos) def _execute_router(self, pacman_report_state): """ exectes the router algorithum :param pacman_report_state: :return: """ # set up a default placer algorithm if none are specified if self._router_algorithm is None: self._router_algorithm = BasicDijkstraRouting() else: self._router_algorithm = self._router_algorithm() self._router_tables = \ self._router_algorithm.route( self._routing_infos, self._placements, self._machine, self._partitioned_graph) if pacman_report_state is not None and \ pacman_report_state.router_report: pacman_reports.router_reports( graph=self._partitionable_graph, hostname=self._hostname, graph_to_sub_graph_mapper=self._graph_mapper, placements=self._placements, report_folder=self._report_default_directory, include_dat_based=pacman_report_state.router_dat_based_report, routing_tables=self._router_tables, routing_info=self._routing_infos, machine=self._machine) if self._in_debug_mode: # check that all routes are valid and no cycles exist valid_route_checker = ValidRouteChecker( placements=self._placements, routing_infos=self._routing_infos, routing_tables=self._router_tables, machine=self._machine, partitioned_graph=self._partitioned_graph) valid_route_checker.validate_routes() def _execute_partitioner(self, pacman_report_state): """ executes the partitioner function :param pacman_report_state: :return: """ # execute partitioner or default partitioner (as seen fit) if self._partitioner_algorithm is None: self._partitioner_algorithm = BasicPartitioner() else: self._partitioner_algorithm = self._partitioner_algorithm() # execute partitioner self._partitioned_graph, self._graph_mapper = \ self._partitioner_algorithm.partition(self._partitionable_graph, self._machine) # execute reports if (pacman_report_state is not None and pacman_report_state.partitioner_report): pacman_reports.partitioner_reports( self._report_default_directory, self._hostname, self._partitionable_graph, self._graph_mapper) def _execute_placer(self, pacman_report_state): """ executes the placer :param pacman_report_state: :return: """ # execute placer or default placer (as seen fit) if self._placer_algorithm is None: self._placer_algorithm = BasicPlacer() else: self._placer_algorithm = self._placer_algorithm() # execute placer self._placements = self._placer_algorithm.place( self._partitioned_graph, self._machine) # execute placer reports if needed if (pacman_report_state is not None and pacman_report_state.placer_report): pacman_reports.placer_reports_with_partitionable_graph( graph=self._partitionable_graph, graph_mapper=self._graph_mapper, hostname=self._hostname, machine=self._machine, placements=self._placements, report_folder=self._report_default_directory) def generate_data_specifications(self): """ generates the dsg for the graph. :return: """ # iterate though subvertexes and call generate_data_spec for each # vertex executable_targets = ExecutableTargets() # create a progress bar for end users progress_bar = ProgressBar(len(list(self._placements.placements)), "on generating data specifications") for placement in self._placements.placements: associated_vertex =\ self._graph_mapper.get_vertex_from_subvertex( placement.subvertex) # if the vertex can generate a DSG, call it if isinstance(associated_vertex, AbstractDataSpecableVertex): ip_tags = self._tags.get_ip_tags_for_vertex( placement.subvertex) reverse_ip_tags = self._tags.get_reverse_ip_tags_for_vertex( placement.subvertex) associated_vertex.generate_data_spec( placement.subvertex, placement, self._partitioned_graph, self._partitionable_graph, self._routing_infos, self._hostname, self._graph_mapper, self._report_default_directory, ip_tags, reverse_ip_tags, self._writeTextSpecs, self._app_data_runtime_folder) progress_bar.update() # Get name of binary from vertex binary_name = associated_vertex.get_binary_file_name() # Attempt to find this within search paths binary_path = executable_finder.get_executable_path( binary_name) if binary_path is None: raise exceptions.ExecutableNotFoundException(binary_name) if not executable_targets.has_binary(binary_path): executable_targets.add_binary(binary_path) executable_targets.add_processor( binary_path, placement.x, placement.y, placement.p) # finish the progress bar progress_bar.end() return executable_targets def add_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge( self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_edge(edge) # add any dependent edges and verts if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_edge(dependant_edge) def add_edge(self, edge_to_add): """ :param edge_to_add: :return: """ self._partitionable_graph.add_edge(edge_to_add) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population( size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def create_projection( self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: :param postsynaptic_population: :param connector: :param source: :param target: :param synapse_dynamics: :param label: :param rng: :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection( presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor) def _add_virtual_chips(self): # allocate chip ids to the virutal chips chip_id_allocator = MallocBasedChipIdAllocator() chip_id_allocator.allocate_chip_ids(self._partitionable_graph, self._machine) # add virtual chips to the machine object for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractVirtualVertex): # check if the virtual chip doesn't already exist if self._machine.get_chip_at(vertex.virtual_chip_x, vertex.virtual_chip_y) is None: virutal_chip = self._create_virtual_chip(vertex) self._machine.add_chip(virutal_chip) def _create_virtual_chip(self, virtual_vertex): """ Create a virtual chip as a real chip in the spinnmachine machine\ object :param virtual_vertex: virutal vertex to convert into a real chip :return: the real chip """ sdram_object = SDRAM() # creates the two links spinnaker_link_id = virtual_vertex.get_spinnaker_link_id spinnaker_link_data = \ self._machine.locate_connected_chips_coords_and_link( config.getint("Machine", "version"), spinnaker_link_id) virtual_link_id = (spinnaker_link_data.connected_link + 3) % 6 to_virtual_chip_link = Link( destination_x=virtual_vertex.virtual_chip_x, destination_y=virtual_vertex.virtual_chip_y, source_x=spinnaker_link_data.connected_chip_x, source_y=spinnaker_link_data.connected_chip_y, multicast_default_from=virtual_link_id, multicast_default_to=virtual_link_id, source_link_id=spinnaker_link_data.connected_link) from_virtual_chip_link = Link( destination_x=spinnaker_link_data.connected_chip_x, destination_y=spinnaker_link_data.connected_chip_y, source_x=virtual_vertex.virtual_chip_x, source_y=virtual_vertex.virtual_chip_y, multicast_default_from=(spinnaker_link_data.connected_link), multicast_default_to=spinnaker_link_data.connected_link, source_link_id=virtual_link_id) # create the router links = [from_virtual_chip_link] router_object = MachineRouter( links=links, emergency_routing_enabled=False, clock_speed=MachineRouter.ROUTER_DEFAULT_CLOCK_SPEED, n_available_multicast_entries=sys.maxint) # create the processors processors = list() for virtual_core_id in range(0, 128): processors.append(Processor(virtual_core_id, Processor.CPU_AVAILABLE, virtual_core_id == 0)) # connect the real chip with the virtual one connected_chip = self._machine.get_chip_at( spinnaker_link_data.connected_chip_x, spinnaker_link_data.connected_chip_y) connected_chip.router.add_link(to_virtual_chip_link) # return new v chip return Chip( processors=processors, router=router_object, sdram=sdram_object, x=virtual_vertex.virtual_chip_x, y=virtual_vertex.virtual_chip_y, virtual=True, nearest_ethernet_x=None, nearest_ethernet_y=None) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None): """ :param turn_off_machine: decides if the machine should be powered down\ after running the exeuction. Note that this powers down all boards\ connected to the BMP connections given to the transciever :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :return: None """ for population in self._populations: population._end() if turn_off_machine is None: config.getboolean("Machine", "turn_off_machine") if clear_routing_tables is None: config.getboolean("Machine", "clear_routing_tables") if clear_tags is None: config.getboolean("Machine", "clear_tags") # if stopping on machine, clear iptags and if clear_tags: for ip_tag in self._tags.ip_tags: self._txrx.clear_ip_tag( ip_tag.tag, board_address=ip_tag.board_address) for reverse_ip_tag in self._tags.reverse_ip_tags: self._txrx.clear_ip_tag( reverse_ip_tag.tag, board_address=reverse_ip_tag.board_address) # if clearing routing table entries, clear if clear_routing_tables: for router_table in self._router_tables.routing_tables: if not self._machine.get_chip_at(router_table.x, router_table.y).virtual: self._txrx.clear_multicast_routes(router_table.x, router_table.y) # execute app stop # self._txrx.stop_application(self._app_id) if self._create_database: self._database_interface.stop() # if asked to turn off machine, power down each rack via bmp # connections if turn_off_machine: self._txrx.power_off_machine() # stop the transciever self._txrx.close() def _add_socket_address(self, socket_address): """ :param socket_address: :return: """ self._database_socket_addresses.add(socket_address)
class Spinnaker(SpinnakerMainInterface): """ Spinnaker: the main entrance for the spynnaker front end """ def __init__( self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None, n_chips_required=None): # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) # population holders self._populations = list() self._projections = list() self._multi_cast_vertex = None self._edge_count = 0 self._live_spike_recorder = dict() # create xml path for where to locate spynnaker related functions when # using auto pause and resume extra_algorithm_xml_path = list() extra_algorithm_xml_path.append(os.path.join( os.path.dirname(overridden_pacman_functions.__file__), "algorithms_metadata.xml")) extra_mapping_inputs = dict() extra_mapping_inputs['CreateAtomToEventIdMapping'] = config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping") SpinnakerMainInterface.__init__( self, config, graph_label=graph_label, executable_finder=executable_finder, database_socket_addresses=database_socket_addresses, extra_algorithm_xml_paths=extra_algorithm_xml_path, extra_mapping_inputs=extra_mapping_inputs, n_chips_required=n_chips_required) # timing parameters self._min_supported_delay = None self._max_supported_delay = None self._time_scale_factor = None # set up machine targeted data self._set_up_timings(timestep, min_delay, max_delay) self.set_up_machine_specifics(host_name) logger.info("Setting time scale factor to {}." .format(self._time_scale_factor)) # get the machine time step logger.info("Setting machine time step to {} micro-seconds." .format(self._machine_time_step)) def _set_up_timings(self, timestep, min_delay, max_delay): self._machine_time_step = config.getint("Machine", "machineTimeStep") # deal with params allowed via the setup options if timestep is not None: # convert into milliseconds from microseconds timestep *= 1000 self._machine_time_step = timestep if min_delay is not None and float(min_delay * 1000) < 1.0 * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support min delays below {} ms with the " "current machine time step" .format(constants.MIN_SUPPORTED_DELAY * timestep)) natively_supported_delay_for_models = \ constants.MAX_SUPPORTED_DELAY_TICS delay_extension_max_supported_delay = \ constants.MAX_DELAY_BLOCKS \ * constants.MAX_TIMER_TICS_SUPPORTED_PER_BLOCK max_delay_tics_supported = \ natively_supported_delay_for_models + \ delay_extension_max_supported_delay if max_delay is not None\ and float(max_delay * 1000) > max_delay_tics_supported * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support max delays above {} ms with the " "current machine time step".format(0.144 * timestep)) if min_delay is not None: self._min_supported_delay = min_delay else: self._min_supported_delay = timestep / 1000.0 if max_delay is not None: self._max_supported_delay = max_delay else: self._max_supported_delay = (max_delay_tics_supported * (timestep / 1000.0)) if (config.has_option("Machine", "timeScaleFactor") and config.get("Machine", "timeScaleFactor") != "None"): self._time_scale_factor = \ config.getint("Machine", "timeScaleFactor") if timestep * self._time_scale_factor < 1000: if config.getboolean( "Mode", "violate_1ms_wall_clock_restriction"): logger.warn( "****************************************************") logger.warn( "*** The combination of simulation time step and ***") logger.warn( "*** the machine time scale factor results in a ***") logger.warn( "*** wall clock timer tick that is currently not ***") logger.warn( "*** reliably supported by the spinnaker machine. ***") logger.warn( "****************************************************") else: raise common_exceptions.ConfigurationException( "The combination of simulation time step and the" " machine time scale factor results in a wall clock " "timer tick that is currently not reliably supported " "by the spinnaker machine. If you would like to " "override this behaviour (at your own risk), please " "add violate_1ms_wall_clock_restriction = True to the " "[Mode] section of your .spynnaker.cfg file") else: self._time_scale_factor = max(1, math.ceil(1000.0 / float(timestep))) if self._time_scale_factor > 1: logger.warn("A timestep was entered that has forced sPyNNaker " "to automatically slow the simulation down from " "real time by a factor of {}. To remove this " "automatic behaviour, please enter a " "timescaleFactor value in your .spynnaker.cfg" .format(self._time_scale_factor)) def _detect_if_graph_has_changed(self, reset_flags=True): """ Iterates though the graph and looks changes """ changed = False for population in self._populations: if population.requires_mapping: changed = True if reset_flags: population.mark_no_changes() for projection in self._projections: if projection.requires_mapping: changed = True if reset_flags: projection.mark_no_changes() return changed @property def min_supported_delay(self): """ The minimum supported delay based in milliseconds """ return self._min_supported_delay @property def max_supported_delay(self): """ The maximum supported delay based in milliseconds """ return self._max_supported_delay def add_partitionable_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_partitionable_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge( self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_partitionable_edge(edge) # add any dependent edges and vertices if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_partitionable_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_partitionable_edge( dependant_edge, vertex_to_add.edge_partition_identifier_for_dependent_edge) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population( size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def _add_projection(self, projection): """ Called by each projection to add itself to the list """ self._projections.append(projection) def create_projection( self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: source pop this projection goes from :param postsynaptic_population: dest pop this projection goes to :param connector: the definition of which neurons connect to each other :param source: :param target: type of projection :param synapse_dynamics: plasticity object :param label: human readable version of the projection :param rng: the random number generator to use on this projection :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection( presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor, user_max_delay=self.max_supported_delay) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None, extract_provenance_data=True, extract_iobuf=True): """ :param turn_off_machine: decides if the machine should be powered down\ after running the execution. Note that this powers down all boards\ connected to the BMP connections given to the transceiver :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :param extract_provenance_data: informs the tools if it should \ try to extract provenance data. :type extract_provenance_data: bool :param extract_iobuf: tells the tools if it should try to \ extract iobuf :type extract_iobuf: bool :return: None """ for population in self._populations: population._end() SpinnakerMainInterface.stop( self, turn_off_machine, clear_routing_tables, clear_tags, extract_provenance_data, extract_iobuf) def run(self, run_time): """ Run the model created :param run_time: the time in ms to run the simulation for """ # extra post run algorithms self._dsg_algorithm = "SpynnakerDataSpecificationWriter" SpinnakerMainInterface.run(self, run_time)
class Spinnaker(object): def __init__(self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None): self._hostname = host_name # update graph label if needed if graph_label is None: graph_label = "Application_graph" # delays parameters self._min_supported_delay = None self._max_supported_delay = None # pacman objects self._partitionable_graph = PartitionableGraph(label=graph_label) self._partitioned_graph = None self._graph_mapper = None self._placements = None self._router_tables = None self._routing_infos = None self._tags = None self._machine = None self._txrx = None self._reports_states = None self._app_id = None self._buffer_manager = None # database objects self._database_socket_addresses = set() if database_socket_addresses is not None: self._database_socket_addresses.union(database_socket_addresses) self._database_interface = None self._create_database = None self._database_file_path = None # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) # population holders self._populations = list() self._projections = list() self._multi_cast_vertex = None self._edge_count = 0 self._live_spike_recorder = dict() # holder for the executable targets (which we will need for reset and # pause and resume functionality self._executable_targets = None # holders for data needed for reset when nothing changes in the # application graph self._processor_to_app_data_base_address_mapper = None self._placement_to_app_data_file_paths = None # holder for timing related values self._has_ran = False self._has_reset_last = False self._current_run_ms = 0 self._no_machine_time_steps = None self._machine_time_step = None self._no_sync_changes = 0 # state thats needed the first time around if self._app_id is None: self._app_id = config.getint("Machine", "appID") if config.getboolean("Reports", "reportsEnabled"): self._reports_states = ReportState( config.getboolean("Reports", "writePartitionerReports"), config.getboolean("Reports", "writePlacerReportWithPartitionable"), config.getboolean("Reports", "writePlacerReportWithoutPartitionable"), config.getboolean("Reports", "writeRouterReports"), config.getboolean("Reports", "writeRouterInfoReport"), config.getboolean("Reports", "writeTextSpecs"), config.getboolean("Reports", "writeReloadSteps"), config.getboolean("Reports", "writeTransceiverReport"), config.getboolean("Reports", "outputTimesForSections"), config.getboolean("Reports", "writeTagAllocationReports")) # set up reports default folder self._report_default_directory, this_run_time_string = \ helpful_functions.set_up_report_specifics( default_report_file_path=config.get( "Reports", "defaultReportFilePath"), max_reports_kept=config.getint( "Reports", "max_reports_kept"), app_id=self._app_id) # set up application report folder self._app_data_runtime_folder = \ helpful_functions.set_up_output_application_data_specifics( max_application_binaries_kept=config.getint( "Reports", "max_application_binaries_kept"), where_to_write_application_data_files=config.get( "Reports", "defaultApplicationDataFilePath"), app_id=self._app_id, this_run_time_string=this_run_time_string) self._spikes_per_second = float(config.getfloat( "Simulation", "spikes_per_second")) self._ring_buffer_sigma = float(config.getfloat( "Simulation", "ring_buffer_sigma")) # set up machine targeted data self._set_up_machine_specifics(timestep, min_delay, max_delay, host_name) logger.info("Setting time scale factor to {}." .format(self._time_scale_factor)) logger.info("Setting appID to %d." % self._app_id) # get the machine time step logger.info("Setting machine time step to {} micro-seconds." .format(self._machine_time_step)) def _set_up_machine_specifics(self, timestep, min_delay, max_delay, hostname): self._machine_time_step = config.getint("Machine", "machineTimeStep") # deal with params allowed via the setup options if timestep is not None: # convert into milliseconds from microseconds timestep *= 1000 self._machine_time_step = timestep if min_delay is not None and float(min_delay * 1000) < 1.0 * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support min delays below {} ms with the " "current machine time step" .format(constants.MIN_SUPPORTED_DELAY * timestep)) natively_supported_delay_for_models = \ constants.MAX_SUPPORTED_DELAY_TICS delay_extention_max_supported_delay = \ constants.MAX_DELAY_BLOCKS \ * constants.MAX_TIMER_TICS_SUPPORTED_PER_BLOCK max_delay_tics_supported = \ natively_supported_delay_for_models + \ delay_extention_max_supported_delay if max_delay is not None\ and float(max_delay * 1000) > max_delay_tics_supported * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support max delays above {} ms with the " "current machine time step".format(0.144 * timestep)) if min_delay is not None: self._min_supported_delay = min_delay else: self._min_supported_delay = timestep / 1000.0 if max_delay is not None: self._max_supported_delay = max_delay else: self._max_supported_delay = (max_delay_tics_supported * (timestep / 1000.0)) if (config.has_option("Machine", "timeScaleFactor") and config.get("Machine", "timeScaleFactor") != "None"): self._time_scale_factor = \ config.getint("Machine", "timeScaleFactor") if timestep * self._time_scale_factor < 1000: logger.warn("the combination of machine time step and the " "machine time scale factor results in a real " "timer tick that is currently not reliably " "supported by the spinnaker machine.") else: self._time_scale_factor = max(1, math.ceil(1000.0 / float(timestep))) if self._time_scale_factor > 1: logger.warn("A timestep was entered that has forced pacman103 " "to automatically slow the simulation down from " "real time by a factor of {}. To remove this " "automatic behaviour, please enter a " "timescaleFactor value in your .pacman.cfg" .format(self._time_scale_factor)) if hostname is not None: self._hostname = hostname logger.warn("The machine name from PYNN setup is overriding the " "machine name defined in the spynnaker.cfg file") elif config.has_option("Machine", "machineName"): self._hostname = config.get("Machine", "machineName") else: raise Exception("A SpiNNaker machine must be specified in " "spynnaker.cfg.") use_virtual_board = config.getboolean("Machine", "virtual_board") if self._hostname == 'None' and not use_virtual_board: raise Exception("A SpiNNaker machine must be specified in " "spynnaker.cfg.") def run(self, run_time): """ :param run_time: :return: """ logger.info("Starting execution process") # calculate number of machine time steps total_run_time = self._calculate_number_of_machine_time_steps(run_time) # Calculate the first machine time step to start from and set this # where necessary first_machine_time_step = int(math.ceil( (self._current_run_ms * 1000.0) / self._machine_time_step)) for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractHasFirstMachineTimeStep): vertex.set_first_machine_time_step(first_machine_time_step) # get inputs inputs, application_graph_changed = \ self._create_pacman_executor_inputs(run_time) if application_graph_changed and self._has_ran: raise common_exceptions.ConfigurationException( "Changes to the application graph are not currently supported;" " please instead call p.reset(), p.end(), add changes and then" " call p.setup()") # if the application graph has changed and you've already ran, kill old # stuff running on machine if application_graph_changed and self._has_ran: self._txrx.stop_application(self._app_id) # get outputs required_outputs = self._create_pacman_executor_outputs( requires_reset=False, application_graph_changed=application_graph_changed) # algorithms listing algorithms = self._create_algorithm_list( config.get("Mode", "mode") == "Debug", application_graph_changed, executing_reset=False) # xml paths to the algorithms metadata xml_paths = self._create_xml_paths() # run pacman executor pacman_exeuctor = helpful_functions.do_mapping( inputs, algorithms, required_outputs, xml_paths, config.getboolean("Reports", "outputTimesForSections")) # gather provenance data from the executor itself if needed if (config.get("Reports", "writeProvanceData") and not config.getboolean("Machine", "virtual_board")): pacman_executor_file_path = os.path.join( pacman_exeuctor.get_item("ProvenanceFilePath"), "PACMAN_provancence_data.xml") pacman_exeuctor.write_provenance_data_in_xml( pacman_executor_file_path, pacman_exeuctor.get_item("MemoryTransciever")) # sort out outputs data if application_graph_changed: self._update_data_structures_from_pacman_exeuctor(pacman_exeuctor) else: self._no_sync_changes = pacman_exeuctor.get_item("NoSyncChanges") self._has_ran = pacman_exeuctor.get_item("RanToken") # reset the reset flag to say the last thing was not a reset call self._current_run_ms = total_run_time # switch the reset last flag, as now the last thing to run is a run self._has_reset_last = False def reset(self): """ Code that puts the simulation back at time zero :return: """ logger.info("Starting reset progress") inputs, application_graph_changed = \ self._create_pacman_executor_inputs( this_run_time=0, is_resetting=True) if self._has_ran and application_graph_changed: raise common_exceptions.ConfigurationException( "Resetting the simulation after changing the model" " is not supported") algorithms = self._create_algorithm_list( config.get("Mode", "mode") == "Debug", application_graph_changed, executing_reset=True) xml_paths = self._create_xml_paths() required_outputs = self._create_pacman_executor_outputs( requires_reset=True, application_graph_changed=application_graph_changed) # rewind the buffers from the buffer manager, to start at the beginning # of the simulation again and clear buffered out self._buffer_manager.reset() # reset the current count of how many milliseconds the application # has ran for over multiple calls to run self._current_run_ms = 0 # change number of resets as loading the binary again resets the sync\ # to 0 self._no_sync_changes = 0 # sets the has ran into false state, to pretend that its like it has # not ran self._has_ran = False # sets the reset last flag to true, so that when run occurs, the tools # know to update the vertices which need to know a reset has occurred self._has_reset_last = True # reset the n_machine_time_steps from each vertex for vertex in self.partitionable_graph.vertices: vertex.set_no_machine_time_steps(0) # execute reset functionality helpful_functions.do_mapping( inputs, algorithms, required_outputs, xml_paths, config.getboolean("Reports", "outputTimesForSections")) # if graph has changed kill all old objects as they will need to be # rebuilt at next run if application_graph_changed: self._placements = self._router_tables = self._routing_infos = \ self._tags = self._graph_mapper = self._partitioned_graph = \ self._database_interface = self._executable_targets = \ self._placement_to_app_data_file_paths = \ self._processor_to_app_data_base_address_mapper = None def _update_data_structures_from_pacman_exeuctor(self, pacman_exeuctor): """ Updates all the spinnaker local data structures that it needs from\ the pacman executor :param pacman_exeuctor: the pacman executor required to extract data\ structures from. :return: """ if not config.getboolean("Machine", "virtual_board"): self._txrx = pacman_exeuctor.get_item("MemoryTransciever") self._has_ran = pacman_exeuctor.get_item("RanToken") self._executable_targets = \ pacman_exeuctor.get_item("ExecutableTargets") self._buffer_manager = pacman_exeuctor.get_item("BufferManager") self._processor_to_app_data_base_address_mapper = \ pacman_exeuctor.get_item("ProcessorToAppDataBaseAddress") self._placement_to_app_data_file_paths = \ pacman_exeuctor.get_item("PlacementToAppDataFilePaths") self._placements = pacman_exeuctor.get_item("MemoryPlacements") self._router_tables = \ pacman_exeuctor.get_item("MemoryRoutingTables") self._routing_infos = \ pacman_exeuctor.get_item("MemoryRoutingInfos") self._tags = pacman_exeuctor.get_item("MemoryTags") self._graph_mapper = pacman_exeuctor.get_item("MemoryGraphMapper") self._partitioned_graph = \ pacman_exeuctor.get_item("MemoryPartitionedGraph") self._machine = pacman_exeuctor.get_item("MemoryMachine") self._database_interface = \ pacman_exeuctor.get_item("DatabaseInterface") self._database_file_path = \ pacman_exeuctor.get_item("DatabaseFilePath") self._no_sync_changes = pacman_exeuctor.get_item("NoSyncChanges") @staticmethod def _create_xml_paths(): # add the extra xml files from the config file xml_paths = config.get("Mapping", "extra_xmls_paths") if xml_paths == "None": xml_paths = list() else: xml_paths = xml_paths.split(",") # add extra xml paths for pynn algorithms xml_paths.append( os.path.join(os.path.dirname(overridden_pacman_functions.__file__), "algorithms_metadata.xml")) xml_paths.append(os.path.join(os.path.dirname( pacman_algorithm_reports.__file__), "reports_metadata.xml")) return xml_paths def _create_algorithm_list( self, in_debug_mode, application_graph_changed, executing_reset): algorithms = list() # if you've not ran before, add the buffer manager if (application_graph_changed and not config.getboolean("Machine", "virtual_board")): algorithms.append("FrontEndCommonBufferManagerCreater") # if you're needing a reset, you need to clean the binaries # (unless you've not ran yet) if executing_reset and self._has_ran: # kill binaries # TODO: when SARK 1.34 appears, this only needs to send a signal algorithms.append("FrontEndCommonApplicationExiter") # if the allocation graph has changed, need to go through mapping if application_graph_changed and not executing_reset: # if the system has ran before, kill the apps and run mapping # add debug algorithms if needed if in_debug_mode: algorithms.append("ValidRoutesChecker") algorithm_names = \ config.get("Mapping", "algorithms") algorithm_strings = algorithm_names.split(",") for algorithm_string in algorithm_strings: split_string = algorithm_string.split(":") if len(split_string) == 1: algorithms.append(split_string[0]) else: raise common_exceptions.ConfigurationException( "The tool chain expects config params of list of 1 " "element with ,. Where the elements are either: the " "algorithum_name:algorithm_config_file_path, or " "algorithum_name if its a interal to pacman algorithm." " Please rectify this and try again") # if using virtual machine, add to list of algorithms the virtual # machine generator, otherwise add the standard machine generator if config.getboolean("Machine", "virtual_board"): algorithms.append("FrontEndCommonVirtualMachineInterfacer") else: # protect against the situation where the system has already # got a transceiver (overriding does not lose sockets) if self._txrx is not None: self._txrx.close() self._txrx = None algorithms.append("FrontEndCommonMachineInterfacer") algorithms.append("FrontEndCommonApplicationRunner") algorithms.append("FrontEndCommonNotificationProtocol") algorithms.append( "FrontEndCommonPartitionableGraphApplicationDataLoader") algorithms.append("FrontEndCommonPartitionableGraphHost" "ExecuteDataSpecification") algorithms.append("FrontEndCommomLoadExecutableImages") algorithms.append("FrontEndCommonRoutingTableLoader") algorithms.append("FrontEndCommonTagsLoader") algorithms.append("FrontEndCommomPartitionableGraphData" "SpecificationWriter") # if the end user wants reload script, add the reload script # creator to the list (reload script currently only supported # for the original run) if (not self._has_ran and config.getboolean("Reports", "writeReloadSteps")): algorithms.append("FrontEndCommonReloadScriptCreator") elif (self.has_ran and config.getboolean("Reports", "writeReloadSteps")): logger.warn( "The reload script cannot handle multi-runs, nor can" "it handle resets, therefore it will only contain the " "initial run") if (config.getboolean("Reports", "writeMemoryMapReport") and not config.getboolean("Machine", "virtual_board")): algorithms.append("FrontEndCommonMemoryMapReport") if config.getboolean("Reports", "writeNetworkSpecificationReport"): algorithms.append( "FrontEndCommonNetworkSpecificationPartitionableReport") # if going to write provenance data after the run add the two # provenance gatherers if (config.get("Reports", "writeProvanceData") and not config.getboolean("Machine", "virtual_board")): algorithms.append("FrontEndCommonProvenanceGatherer") # define mapping between output types and reports if self._reports_states is not None \ and self._reports_states.tag_allocation_report: algorithms.append("TagReport") if self._reports_states is not None \ and self._reports_states.routing_info_report: algorithms.append("routingInfoReports") if self._reports_states is not None \ and self._reports_states.router_report: algorithms.append("RouterReports") if self._reports_states is not None \ and self._reports_states.partitioner_report: algorithms.append("PartitionerReport") if (self._reports_states is not None and self._reports_states. placer_report_with_partitionable_graph): algorithms.append("PlacerReportWithPartitionableGraph") if (self._reports_states is not None and self._reports_states. placer_report_without_partitionable_graph): algorithms.append("PlacerReportWithoutPartitionableGraph") else: # add function for extracting all the recorded data from # recorded populations if self._has_ran and not executing_reset: algorithms.append("SpyNNakerRecordingExtractor") # add functions for updating the models algorithms.append("FrontEndCommonRuntimeUpdater") if not self._has_ran and not executing_reset: algorithms.append( "FrontEndCommonPartitionableGraphApplicationDataLoader") algorithms.append("FrontEndCommomLoadExecutableImages") if not executing_reset: algorithms.append("FrontEndCommonNotificationProtocol") # add functions for setting off the models again algorithms.append("FrontEndCommonApplicationRunner") # if going to write provenance data after the run add the two # provenance gatherers if config.get("Reports", "writeProvanceData"): algorithms.append("FrontEndCommonProvenanceGatherer") return algorithms def _create_pacman_executor_outputs( self, requires_reset, application_graph_changed): # explicitly define what outputs spynnaker expects required_outputs = list() if config.getboolean("Machine", "virtual_board"): if application_graph_changed: required_outputs.extend([ "MemoryPlacements", "MemoryRoutingTables", "MemoryRoutingInfos", "MemoryTags", "MemoryPartitionedGraph", "MemoryGraphMapper"]) else: if not requires_reset: required_outputs.append("RanToken") # if front end wants reload script, add requires reload token if (config.getboolean("Reports", "writeReloadSteps") and not self._has_ran and application_graph_changed and not config.getboolean("Machine", "virtual_board")): required_outputs.append("ReloadToken") return required_outputs def _create_pacman_executor_inputs( self, this_run_time, is_resetting=False): application_graph_changed = \ self._detect_if_graph_has_changed(not is_resetting) inputs = list() # file path to store any provenance data to provenance_file_path = \ os.path.join(self._report_default_directory, "provance_data") if not os.path.exists(provenance_file_path): os.mkdir(provenance_file_path) # all modes need the NoSyncChanges if application_graph_changed: self._no_sync_changes = 0 inputs.append( {'type': "NoSyncChanges", 'value': self._no_sync_changes}) # support resetting the machine during start up if (config.getboolean("Machine", "reset_machine_on_startup") and not self._has_ran and not is_resetting): inputs.append( {"type": "ResetMachineOnStartupFlag", 'value': True}) else: inputs.append( {"type": "ResetMachineOnStartupFlag", 'value': False}) # support runtime updater if self._has_ran and not is_resetting: no_machine_time_steps =\ int((this_run_time * 1000.0) / self._machine_time_step) inputs.append({'type': "RunTimeMachineTimeSteps", 'value': no_machine_time_steps}) # FrontEndCommonPartitionableGraphApplicationDataLoader after a # reset and no changes if not self._has_ran and not application_graph_changed: inputs.append(({ 'type': "ProcessorToAppDataBaseAddress", "value": self._processor_to_app_data_base_address_mapper})) inputs.append({"type": "PlacementToAppDataFilePaths", 'value': self._placement_to_app_data_file_paths}) inputs.append({'type': "WriteCheckerFlag", 'value': config.getboolean( "Mode", "verify_writes")}) # support resetting when there's changes in the application graph # (only need to exit) if application_graph_changed and is_resetting: inputs.append({"type": "MemoryTransciever", 'value': self._txrx}) inputs.append({'type': "ExecutableTargets", 'value': self._executable_targets}) inputs.append({'type': "MemoryPlacements", 'value': self._placements}) inputs.append({'type': "MemoryGraphMapper", 'value': self._graph_mapper}) inputs.append({'type': "APPID", 'value': self._app_id}) inputs.append({'type': "RanToken", 'value': self._has_ran}) elif application_graph_changed and not is_resetting: # make a folder for the json files to be stored in json_folder = os.path.join( self._report_default_directory, "json_files") if not os.path.exists(json_folder): os.mkdir(json_folder) # translate config "None" to None width = config.get("Machine", "width") height = config.get("Machine", "height") if width == "None": width = None else: width = int(width) if height == "None": height = None else: height = int(height) number_of_boards = config.get("Machine", "number_of_boards") if number_of_boards == "None": number_of_boards = None scamp_socket_addresses = config.get("Machine", "scamp_connections_data") if scamp_socket_addresses == "None": scamp_socket_addresses = None boot_port_num = config.get("Machine", "boot_connection_port_num") if boot_port_num == "None": boot_port_num = None else: boot_port_num = int(boot_port_num) inputs.append({'type': "MemoryPartitionableGraph", 'value': self._partitionable_graph}) inputs.append({'type': 'ReportFolder', 'value': self._report_default_directory}) inputs.append({'type': "ApplicationDataFolder", 'value': self._app_data_runtime_folder}) inputs.append({'type': 'IPAddress', 'value': self._hostname}) # basic input stuff inputs.append({'type': "BMPDetails", 'value': config.get("Machine", "bmp_names")}) inputs.append({'type': "DownedChipsDetails", 'value': config.get("Machine", "down_chips")}) inputs.append({'type': "DownedCoresDetails", 'value': config.get("Machine", "down_cores")}) inputs.append({'type': "BoardVersion", 'value': config.getint("Machine", "version")}) inputs.append({'type': "NumberOfBoards", 'value': number_of_boards}) inputs.append({'type': "MachineWidth", 'value': width}) inputs.append({'type': "MachineHeight", 'value': height}) inputs.append({'type': "AutoDetectBMPFlag", 'value': config.getboolean("Machine", "auto_detect_bmp")}) inputs.append({'type': "EnableReinjectionFlag", 'value': config.getboolean("Machine", "enable_reinjection")}) inputs.append({'type': "ScampConnectionData", 'value': scamp_socket_addresses}) inputs.append({'type': "BootPortNum", 'value': boot_port_num}) inputs.append({'type': "APPID", 'value': self._app_id}) inputs.append({'type': "RunTime", 'value': this_run_time}) inputs.append({'type': "TimeScaleFactor", 'value': self._time_scale_factor}) inputs.append({'type': "MachineTimeStep", 'value': self._machine_time_step}) inputs.append({'type': "DatabaseSocketAddresses", 'value': self._database_socket_addresses}) inputs.append({'type': "DatabaseWaitOnConfirmationFlag", 'value': config.getboolean( "Database", "wait_on_confirmation")}) inputs.append({'type': "WriteCheckerFlag", 'value': config.getboolean( "Mode", "verify_writes")}) inputs.append({'type': "WriteTextSpecsFlag", 'value': config.getboolean( "Reports", "writeTextSpecs")}) inputs.append({'type': "ExecutableFinder", 'value': executable_finder}) inputs.append({'type': "MachineHasWrapAroundsFlag", 'value': config.getboolean( "Machine", "requires_wrap_arounds")}) inputs.append({'type': "ReportStates", 'value': self._reports_states}) inputs.append({'type': "UserCreateDatabaseFlag", 'value': config.get("Database", "create_database")}) inputs.append({'type': "ExecuteMapping", 'value': config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping")}) inputs.append({'type': "DatabaseSocketAddresses", 'value': self._database_socket_addresses}) inputs.append({'type': "SendStartNotifications", 'value': config.getboolean( "Database", "send_start_notification")}) inputs.append({'type': "ProvenanceFilePath", 'value': provenance_file_path}) # add paths for each file based version inputs.append({'type': "FileCoreAllocationsFilePath", 'value': os.path.join( json_folder, "core_allocations.json")}) inputs.append({'type': "FileSDRAMAllocationsFilePath", 'value': os.path.join( json_folder, "sdram_allocations.json")}) inputs.append({'type': "FileMachineFilePath", 'value': os.path.join( json_folder, "machine.json")}) inputs.append({'type': "FilePartitionedGraphFilePath", 'value': os.path.join( json_folder, "partitioned_graph.json")}) inputs.append({'type': "FilePlacementFilePath", 'value': os.path.join( json_folder, "placements.json")}) inputs.append({'type': "FileRouingPathsFilePath", 'value': os.path.join( json_folder, "routing_paths.json")}) inputs.append({'type': "FileConstraintsFilePath", 'value': os.path.join( json_folder, "constraints.json")}) if self._has_ran: logger.warn( "The network has changed, and therefore mapping will be" " done again. Any recorded data will be erased.") else: # mapping does not need to be executed, therefore add # the data elements needed for the application runner and # runtime re-setter inputs.append({"type": "BufferManager", "value": self._buffer_manager}) inputs.append({'type': "DatabaseWaitOnConfirmationFlag", 'value': config.getboolean( "Database", "wait_on_confirmation")}) inputs.append({'type': "SendStartNotifications", 'value': config.getboolean( "Database", "send_start_notification")}) inputs.append({'type': "DatabaseInterface", 'value': self._database_interface}) inputs.append({"type": "DatabaseSocketAddresses", 'value': self._database_socket_addresses}) inputs.append({'type': "DatabaseFilePath", 'value': self._database_file_path}) inputs.append({'type': "ExecutableTargets", 'value': self._executable_targets}) inputs.append({'type': "APPID", 'value': self._app_id}) inputs.append({"type": "MemoryTransciever", 'value': self._txrx}) inputs.append({"type": "RunTime", 'value': this_run_time}) inputs.append({'type': "TimeScaleFactor", 'value': self._time_scale_factor}) inputs.append({'type': "LoadedReverseIPTagsToken", 'value': True}) inputs.append({'type': "LoadedIPTagsToken", 'value': True}) inputs.append({'type': "LoadedRoutingTablesToken", 'value': True}) inputs.append({'type': "LoadBinariesToken", 'value': True}) inputs.append({'type': "LoadedApplicationDataToken", 'value': True}) inputs.append({'type': "MemoryPlacements", 'value': self._placements}) inputs.append({'type': "MemoryGraphMapper", 'value': self._graph_mapper}) inputs.append({'type': "MemoryPartitionableGraph", 'value': self._partitionable_graph}) inputs.append({'type': "MemoryExtendedMachine", 'value': self._machine}) inputs.append({'type': "MemoryRoutingTables", 'value': self._router_tables}) inputs.append({'type': "ProvenanceFilePath", 'value': provenance_file_path}) inputs.append({'type': "RanToken", 'value': self._has_ran}) return inputs, application_graph_changed def _calculate_number_of_machine_time_steps(self, next_run_time): total_run_time = next_run_time if next_run_time is not None: total_run_time += self._current_run_ms machine_time_steps = ( (total_run_time * 1000.0) / self._machine_time_step) if machine_time_steps != int(machine_time_steps): logger.warn( "The runtime and machine time step combination result in " "a fractional number of machine time steps") self._no_machine_time_steps = int(math.ceil(machine_time_steps)) else: self._no_machine_time_steps = None for vertex in self._partitionable_graph.vertices: if ((isinstance(vertex, AbstractSpikeRecordable) and vertex.is_recording_spikes()) or (isinstance(vertex, AbstractVRecordable) and vertex.is_recording_v()) or (isinstance(vertex, AbstractGSynRecordable) and vertex.is_recording_gsyn)): raise common_exceptions.ConfigurationException( "recording a population when set to infinite runtime " "is not currently supported") for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractDataSpecableVertex): vertex.set_no_machine_time_steps(self._no_machine_time_steps) return total_run_time def _detect_if_graph_has_changed(self, reset_flags=True): """ Iterates though the graph and looks changes """ changed = False for population in self._populations: if population.requires_mapping: changed = True if reset_flags: population.mark_no_changes() for projection in self._projections: if projection.requires_mapping: changed = True if reset_flags: projection.mark_no_changes() return changed @property def app_id(self): """ :return: """ return self._app_id @property def has_ran(self): """ :return: """ return self._has_ran @property def machine_time_step(self): """ :return: """ return self._machine_time_step @property def no_machine_time_steps(self): """ :return: """ return self._no_machine_time_steps @property def timescale_factor(self): """ :return: """ return self._time_scale_factor @property def spikes_per_second(self): """ :return: """ return self._spikes_per_second @property def ring_buffer_sigma(self): """ :return: """ return self._ring_buffer_sigma @property def get_multi_cast_source(self): """ :return: """ return self._multi_cast_vertex @property def partitioned_graph(self): """ :return: """ return self._partitioned_graph @property def partitionable_graph(self): """ :return: """ return self._partitionable_graph @property def placements(self): """ :return: """ return self._placements @property def transceiver(self): """ :return: """ return self._txrx @property def graph_mapper(self): """ :return: """ return self._graph_mapper @property def routing_infos(self): """ :return: """ return self._routing_infos @property def min_supported_delay(self): """ the min supported delay based in milliseconds :return: """ return self._min_supported_delay @property def max_supported_delay(self): """ the max supported delay based in milliseconds :return: """ return self._max_supported_delay @property def buffer_manager(self): return self._buffer_manager def set_app_id(self, value): """ :param value: :return: """ self._app_id = value def get_current_time(self): """ :return: """ if self._has_ran: return float(self._current_run_ms) return 0.0 def __repr__(self): return "Spinnaker object for machine {}".format(self._hostname) def add_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge( self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_edge(edge) # add any dependent edges and vertices if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_edge( dependant_edge, vertex_to_add.edge_partition_identifier_for_dependent_edge) def add_edge(self, edge_to_add, partition_identifier=None): """ :param edge_to_add: :param partition_identifier: the partition identifier for the outgoing\ edge partition :return: """ self._partitionable_graph.add_edge(edge_to_add, partition_identifier) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population( size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def _add_projection(self, projection): """ called by each projection to add itself to the list :param projection: :return: """ self._projections.append(projection) def create_projection( self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: :param postsynaptic_population: :param connector: :param source: :param target: :param synapse_dynamics: :param label: :param rng: :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection( presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor, user_max_delay=self.max_supported_delay) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None): """ :param turn_off_machine: decides if the machine should be powered down\ after running the execution. Note that this powers down all boards\ connected to the BMP connections given to the transceiver :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :return: None """ for population in self._populations: population._end() # if not a virtual machine, then shut down stuff on the board if not config.getboolean("Machine", "virtual_board"): if turn_off_machine is None: turn_off_machine = \ config.getboolean("Machine", "turn_off_machine") if clear_routing_tables is None: clear_routing_tables = config.getboolean( "Machine", "clear_routing_tables") if clear_tags is None: clear_tags = config.getboolean("Machine", "clear_tags") # if stopping on machine, clear iptags and if clear_tags: for ip_tag in self._tags.ip_tags: self._txrx.clear_ip_tag( ip_tag.tag, board_address=ip_tag.board_address) for reverse_ip_tag in self._tags.reverse_ip_tags: self._txrx.clear_ip_tag( reverse_ip_tag.tag, board_address=reverse_ip_tag.board_address) # if clearing routing table entries, clear if clear_routing_tables: for router_table in self._router_tables.routing_tables: if not self._machine.get_chip_at(router_table.x, router_table.y).virtual: self._txrx.clear_multicast_routes(router_table.x, router_table.y) # clear values self._no_sync_changes = 0 # app stop command self._txrx.stop_application(self._app_id) if self._create_database: self._database_interface.stop() self._buffer_manager.stop() # stop the transceiver if turn_off_machine: logger.info("Turning off machine") self._txrx.close(power_off_machine=turn_off_machine) def _add_socket_address(self, socket_address): """ :param socket_address: :return: """ self._database_socket_addresses.add(socket_address)
class Spinnaker(SpinnakerMainInterface): """ Spinnaker: the main entrance for the spynnaker front end """ def __init__(self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None, n_chips_required=None): # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) # population holders self._populations = list() self._projections = list() self._multi_cast_vertex = None self._edge_count = 0 self._live_spike_recorder = dict() # create xml path for where to locate spynnaker related functions when # using auto pause and resume extra_algorithm_xml_path = list() extra_algorithm_xml_path.append( os.path.join(os.path.dirname(overridden_pacman_functions.__file__), "algorithms_metadata.xml")) extra_mapping_inputs = dict() extra_mapping_inputs['CreateAtomToEventIdMapping'] = config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping") SpinnakerMainInterface.__init__( self, config, graph_label=graph_label, executable_finder=executable_finder, database_socket_addresses=database_socket_addresses, extra_algorithm_xml_paths=extra_algorithm_xml_path, extra_mapping_inputs=extra_mapping_inputs, n_chips_required=n_chips_required) # timing parameters self._min_supported_delay = None self._max_supported_delay = None self._time_scale_factor = None # set up machine targeted data self._set_up_timings(timestep, min_delay, max_delay) self.set_up_machine_specifics(host_name) logger.info("Setting time scale factor to {}.".format( self._time_scale_factor)) # get the machine time step logger.info("Setting machine time step to {} micro-seconds.".format( self._machine_time_step)) def _set_up_timings(self, timestep, min_delay, max_delay): self._machine_time_step = config.getint("Machine", "machineTimeStep") # deal with params allowed via the setup options if timestep is not None: # convert into milliseconds from microseconds timestep *= 1000 self._machine_time_step = timestep if min_delay is not None and float(min_delay * 1000) < 1.0 * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support min delays below {} ms with the " "current machine time step".format( constants.MIN_SUPPORTED_DELAY * timestep)) natively_supported_delay_for_models = \ constants.MAX_SUPPORTED_DELAY_TICS delay_extension_max_supported_delay = \ constants.MAX_DELAY_BLOCKS \ * constants.MAX_TIMER_TICS_SUPPORTED_PER_BLOCK max_delay_tics_supported = \ natively_supported_delay_for_models + \ delay_extension_max_supported_delay if max_delay is not None\ and float(max_delay * 1000) > max_delay_tics_supported * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support max delays above {} ms with the " "current machine time step".format(0.144 * timestep)) if min_delay is not None: self._min_supported_delay = min_delay else: self._min_supported_delay = timestep / 1000.0 if max_delay is not None: self._max_supported_delay = max_delay else: self._max_supported_delay = (max_delay_tics_supported * (timestep / 1000.0)) if (config.has_option("Machine", "timeScaleFactor") and config.get("Machine", "timeScaleFactor") != "None"): self._time_scale_factor = \ config.getint("Machine", "timeScaleFactor") if timestep * self._time_scale_factor < 1000: if config.getboolean("Mode", "violate_1ms_wall_clock_restriction"): logger.warn( "****************************************************") logger.warn( "*** The combination of simulation time step and ***") logger.warn( "*** the machine time scale factor results in a ***") logger.warn( "*** wall clock timer tick that is currently not ***") logger.warn( "*** reliably supported by the spinnaker machine. ***") logger.warn( "****************************************************") else: raise common_exceptions.ConfigurationException( "The combination of simulation time step and the" " machine time scale factor results in a wall clock " "timer tick that is currently not reliably supported " "by the spinnaker machine. If you would like to " "override this behaviour (at your own risk), please " "add violate_1ms_wall_clock_restriction = True to the " "[Mode] section of your .spynnaker.cfg file") else: self._time_scale_factor = max(1, math.ceil(1000.0 / float(timestep))) if self._time_scale_factor > 1: logger.warn( "A timestep was entered that has forced sPyNNaker " "to automatically slow the simulation down from " "real time by a factor of {}. To remove this " "automatic behaviour, please enter a " "timescaleFactor value in your .spynnaker.cfg".format( self._time_scale_factor)) def _detect_if_graph_has_changed(self, reset_flags=True): """ Iterates though the graph and looks changes """ changed = False for population in self._populations: if population.requires_mapping: changed = True if reset_flags: population.mark_no_changes() for projection in self._projections: if projection.requires_mapping: changed = True if reset_flags: projection.mark_no_changes() return changed @property def min_supported_delay(self): """ The minimum supported delay based in milliseconds """ return self._min_supported_delay @property def max_supported_delay(self): """ The maximum supported delay based in milliseconds """ return self._max_supported_delay def add_partitionable_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_partitionable_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge(self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_partitionable_edge(edge) # add any dependent edges and vertices if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_partitionable_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_partitionable_edge( dependant_edge, vertex_to_add.edge_partition_identifier_for_dependent_edge) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population(size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def _add_projection(self, projection): """ Called by each projection to add itself to the list """ self._projections.append(projection) def create_projection(self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: source pop this projection goes from :param postsynaptic_population: dest pop this projection goes to :param connector: the definition of which neurons connect to each other :param source: :param target: type of projection :param synapse_dynamics: plasticity object :param label: human readable version of the projection :param rng: the random number generator to use on this projection :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection(presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor, user_max_delay=self.max_supported_delay) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None, extract_provenance_data=True, extract_iobuf=True): """ :param turn_off_machine: decides if the machine should be powered down\ after running the execution. Note that this powers down all boards\ connected to the BMP connections given to the transceiver :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :param extract_provenance_data: informs the tools if it should \ try to extract provenance data. :type extract_provenance_data: bool :param extract_iobuf: tells the tools if it should try to \ extract iobuf :type extract_iobuf: bool :return: None """ for population in self._populations: population._end() SpinnakerMainInterface.stop(self, turn_off_machine, clear_routing_tables, clear_tags, extract_provenance_data, extract_iobuf) def run(self, run_time): """ Run the model created :param run_time: the time in ms to run the simulation for """ # extra post run algorithms self._dsg_algorithm = "SpynnakerDataSpecificationWriter" SpinnakerMainInterface.run(self, run_time)
class Spinnaker(object): def __init__(self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None): self._hostname = host_name # update graph label if needed if graph_label is None: graph_label = "Application_graph" # delays parameters self._min_supported_delay = None self._max_supported_delay = None # pacman objects self._partitionable_graph = PartitionableGraph(label=graph_label) self._partitioned_graph = None self._graph_mapper = None self._placements = None self._router_tables = None self._routing_infos = None self._tags = None self._machine = None self._txrx = None self._has_ran = False self._reports_states = None self._app_id = None self._runtime = None # database objects self._database_socket_addresses = set() if database_socket_addresses is not None: self._database_socket_addresses.union(database_socket_addresses) self._database_interface = None self._create_database = None # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) # population holders self._populations = list() self._multi_cast_vertex = None self._edge_count = 0 # specific utility vertexes self._live_spike_recorder = dict() # holder for number of times the timer event should execute for the # simulation self._no_machine_time_steps = None self._machine_time_step = None # state thats needed the first time around if self._app_id is None: self._app_id = config.getint("Machine", "appID") if config.getboolean("Reports", "reportsEnabled"): self._reports_states = ReportState( config.getboolean("Reports", "writePartitionerReports"), config.getboolean("Reports", "writePlacerReportWithPartitionable"), config.getboolean("Reports", "writePlacerReportWithoutPartitionable"), config.getboolean("Reports", "writeRouterReports"), config.getboolean("Reports", "writeRouterInfoReport"), config.getboolean("Reports", "writeTextSpecs"), config.getboolean("Reports", "writeReloadSteps"), config.getboolean("Reports", "writeTransceiverReport"), config.getboolean("Reports", "outputTimesForSections"), config.getboolean("Reports", "writeTagAllocationReports")) # set up reports default folder self._report_default_directory, this_run_time_string = \ helpful_functions.set_up_report_specifics( default_report_file_path=config.get( "Reports", "defaultReportFilePath"), max_reports_kept=config.getint( "Reports", "max_reports_kept"), app_id=self._app_id) # set up application report folder self._app_data_runtime_folder = \ helpful_functions.set_up_output_application_data_specifics( max_application_binaries_kept=config.getint( "Reports", "max_application_binaries_kept"), where_to_write_application_data_files=config.get( "Reports", "defaultApplicationDataFilePath"), app_id=self._app_id, this_run_time_string=this_run_time_string) self._spikes_per_second = float(config.getfloat( "Simulation", "spikes_per_second")) self._ring_buffer_sigma = float(config.getfloat( "Simulation", "ring_buffer_sigma")) # set up machine targeted data self._set_up_machine_specifics(timestep, min_delay, max_delay, host_name) logger.info("Setting time scale factor to {}." .format(self._time_scale_factor)) logger.info("Setting appID to %d." % self._app_id) # get the machine time step logger.info("Setting machine time step to {} micro-seconds." .format(self._machine_time_step)) def _set_up_machine_specifics(self, timestep, min_delay, max_delay, hostname): self._machine_time_step = config.getint("Machine", "machineTimeStep") # deal with params allowed via the setup options if timestep is not None: # convert into milliseconds from microseconds timestep *= 1000 self._machine_time_step = timestep if min_delay is not None and float(min_delay * 1000) < 1.0 * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support min delays below {} ms with the " "current machine time step" .format(constants.MIN_SUPPORTED_DELAY * timestep)) natively_supported_delay_for_models = \ constants.MAX_SUPPORTED_DELAY_TICS delay_extention_max_supported_delay = \ constants.MAX_DELAY_BLOCKS \ * constants.MAX_TIMER_TICS_SUPPORTED_PER_BLOCK max_delay_tics_supported = \ natively_supported_delay_for_models + \ delay_extention_max_supported_delay if max_delay is not None\ and float(max_delay * 1000) > max_delay_tics_supported * timestep: raise common_exceptions.ConfigurationException( "Pacman does not support max delays above {} ms with the " "current machine time step".format(0.144 * timestep)) if min_delay is not None: self._min_supported_delay = min_delay else: self._min_supported_delay = timestep / 1000.0 if max_delay is not None: self._max_supported_delay = max_delay else: self._max_supported_delay = (max_delay_tics_supported * (timestep / 1000.0)) if (config.has_option("Machine", "timeScaleFactor") and config.get("Machine", "timeScaleFactor") != "None"): self._time_scale_factor = \ config.getint("Machine", "timeScaleFactor") if timestep * self._time_scale_factor < 1000: logger.warn("the combination of machine time step and the " "machine time scale factor results in a real " "timer tick that is currently not reliably " "supported by the spinnaker machine.") else: self._time_scale_factor = max(1, math.ceil(1000.0 / float(timestep))) if self._time_scale_factor > 1: logger.warn("A timestep was entered that has forced pacman103 " "to automatically slow the simulation down from " "real time by a factor of {}. To remove this " "automatic behaviour, please enter a " "timescaleFactor value in your .pacman.cfg" .format(self._time_scale_factor)) if hostname is not None: self._hostname = hostname logger.warn("The machine name from PYNN setup is overriding the " "machine name defined in the spynnaker.cfg file") elif config.has_option("Machine", "machineName"): self._hostname = config.get("Machine", "machineName") else: raise Exception("A SpiNNaker machine must be specified in " "spynnaker.cfg.") use_virtual_board = config.getboolean("Machine", "virtual_board") if self._hostname == 'None' and not use_virtual_board: raise Exception("A SpiNNaker machine must be specified in " "spynnaker.cfg.") def run(self, run_time): """ :param run_time: :return: """ # calculate number of machine time steps self._calculate_number_of_machine_time_steps(run_time) self._runtime = run_time xml_paths = self._create_xml_paths() inputs = self._create_pacman_executor_inputs() required_outputs = self._create_pacman_executor_outputs() algorithms = self._create_algorithm_list( config.get("Mode", "mode") == "Debug") pacman_exeuctor = helpful_functions.do_mapping( inputs, algorithms, required_outputs, xml_paths, config.getboolean("Reports", "outputTimesForSections")) # gather provenance data from the executor itself if needed if config.get("Reports", "writeProvanceData"): pacman_executor_file_path = os.path.join( pacman_exeuctor.get_item("ProvenanceFilePath"), "PACMAN_provancence_data.xml") pacman_exeuctor.write_provenance_data_in_xml( pacman_executor_file_path, pacman_exeuctor.get_item("MemoryTransciever")) # sort out outputs data self._txrx = pacman_exeuctor.get_item("MemoryTransciever") self._placements = pacman_exeuctor.get_item("MemoryPlacements") self._router_tables = pacman_exeuctor.get_item("MemoryRoutingTables") self._routing_infos = pacman_exeuctor.get_item("MemoryRoutingInfos") self._tags = pacman_exeuctor.get_item("MemoryTags") self._graph_mapper = pacman_exeuctor.get_item("MemoryGraphMapper") self._partitioned_graph = pacman_exeuctor.get_item( "MemoryPartitionedGraph") self._machine = pacman_exeuctor.get_item("MemoryMachine") self._database_interface = pacman_exeuctor.get_item( "DatabaseInterface") self._has_ran = pacman_exeuctor.get_item("RanToken") @staticmethod def _create_xml_paths(): # add the extra xml files from the config file xml_paths = config.get("Mapping", "extra_xmls_paths") if xml_paths == "None": xml_paths = list() else: xml_paths = xml_paths.split(",") # add extra xml paths for pynn algorithms xml_paths.append( os.path.join(os.path.dirname(overridden_pacman_functions.__file__), "algorithms_metadata.xml")) xml_paths.append(os.path.join(os.path.dirname( pacman_algorithm_reports.__file__), "reports_metadata.xml")) return xml_paths def _create_algorithm_list(self, in_debug_mode): algorithms = "" algorithms += (config.get("Mapping", "algorithms") + "," + config.get("Mapping", "interface_algorithms")) # if using virtual machine, add to list of algorithms the virtual # machine generator, otherwise add the standard machine generator if config.getboolean("Machine", "virtual_board"): algorithms += ",FrontEndCommonVirtualMachineInterfacer" else: algorithms += ",FrontEndCommonMachineInterfacer" algorithms += ",FrontEndCommonApplicationRunner" # if going to write provenance data after the run add the two # provenance gatherers if config.get("Reports", "writeProvanceData"): algorithms += ",FrontEndCommonProvenanceGatherer" # if the end user wants reload script, add the reload script # creator to the list if config.getboolean("Reports", "writeReloadSteps"): algorithms += ",FrontEndCommonReloadScriptCreator" if config.getboolean("Reports", "writeMemoryMapReport"): algorithms += ",FrontEndCommonMemoryMapReport" if config.getboolean("Reports", "writeNetworkSpecificationReport"): algorithms += \ ",FrontEndCommonNetworkSpecificationPartitionableReport" # define mapping between output types and reports if self._reports_states is not None \ and self._reports_states.tag_allocation_report: algorithms += ",TagReport" if self._reports_states is not None \ and self._reports_states.routing_info_report: algorithms += ",routingInfoReports" if self._reports_states is not None \ and self._reports_states.router_report: algorithms += ",RouterReports" if self._reports_states is not None \ and self._reports_states.partitioner_report: algorithms += ",PartitionerReport" if (self._reports_states is not None and self._reports_states.placer_report_with_partitionable_graph): algorithms += ",PlacerReportWithPartitionableGraph" if (self._reports_states is not None and self._reports_states .placer_report_without_partitionable_graph): algorithms += ",PlacerReportWithoutPartitionableGraph" # add debug algorithms if needed if in_debug_mode: algorithms += ",ValidRoutesChecker" return algorithms @staticmethod def _create_pacman_executor_outputs(): # explicitly define what outputs spynnaker expects required_outputs = list() if config.getboolean("Machine", "virtual_board"): required_outputs.extend([ "MemoryPlacements", "MemoryRoutingTables", "MemoryRoutingInfos", "MemoryTags", "MemoryPartitionedGraph", "MemoryGraphMapper"]) else: required_outputs.append("RanToken") # if front end wants reload script, add requires reload token if config.getboolean("Reports", "writeReloadSteps"): required_outputs.append("ReloadToken") return required_outputs def _create_pacman_executor_inputs(self): # make a folder for the json files to be stored in json_folder = os.path.join( self._report_default_directory, "json_files") if not os.path.exists(json_folder): os.mkdir(json_folder) # file path to store any provenance data to provenance_file_path = os.path.join(self._report_default_directory, "provance_data") if not os.path.exists(provenance_file_path): os.mkdir(provenance_file_path) # translate config "None" to None width = config.get("Machine", "width") height = config.get("Machine", "height") if width == "None": width = None else: width = int(width) if height == "None": height = None else: height = int(height) number_of_boards = config.get("Machine", "number_of_boards") if number_of_boards == "None": number_of_boards = None scamp_socket_addresses = config.get( "Machine", "scamp_connections_data") if scamp_socket_addresses == "None": scamp_socket_addresses = None boot_port_num = config.get("Machine", "boot_connection_port_num") if boot_port_num == "None": boot_port_num = None else: boot_port_num = int(boot_port_num) inputs = list() inputs.append({'type': "MemoryPartitionableGraph", 'value': self._partitionable_graph}) inputs.append({'type': 'ReportFolder', 'value': self._report_default_directory}) inputs.append({'type': "ApplicationDataFolder", 'value': self._app_data_runtime_folder}) inputs.append({'type': 'IPAddress', 'value': self._hostname}) # basic input stuff inputs.append({'type': "BMPDetails", 'value': config.get("Machine", "bmp_names")}) inputs.append({'type': "DownedChipsDetails", 'value': config.get("Machine", "down_chips")}) inputs.append({'type': "DownedCoresDetails", 'value': config.get("Machine", "down_cores")}) inputs.append({'type': "BoardVersion", 'value': config.getint("Machine", "version")}) inputs.append({'type': "NumberOfBoards", 'value': number_of_boards}) inputs.append({'type': "MachineWidth", 'value': width}) inputs.append({'type': "MachineHeight", 'value': height}) inputs.append({'type': "AutoDetectBMPFlag", 'value': config.getboolean("Machine", "auto_detect_bmp")}) inputs.append({'type': "EnableReinjectionFlag", 'value': config.getboolean("Machine", "enable_reinjection")}) inputs.append({'type': "ScampConnectionData", 'value': scamp_socket_addresses}) inputs.append({'type': "BootPortNum", 'value': boot_port_num}) inputs.append({'type': "APPID", 'value': self._app_id}) inputs.append({'type': "RunTime", 'value': self._runtime}) inputs.append({'type': "TimeScaleFactor", 'value': self._time_scale_factor}) inputs.append({'type': "MachineTimeStep", 'value': self._machine_time_step}) inputs.append({'type': "DatabaseSocketAddresses", 'value': self._database_socket_addresses}) inputs.append({'type': "DatabaseWaitOnConfirmationFlag", 'value': config.getboolean("Database", "wait_on_confirmation")}) inputs.append({'type': "WriteCheckerFlag", 'value': config.getboolean("Mode", "verify_writes")}) inputs.append({'type': "WriteTextSpecsFlag", 'value': config.getboolean("Reports", "writeTextSpecs")}) inputs.append({'type': "ExecutableFinder", 'value': executable_finder}) inputs.append({'type': "MachineHasWrapAroundsFlag", 'value': config.getboolean("Machine", "requires_wrap_arounds")}) inputs.append({'type': "ReportStates", 'value': self._reports_states}) inputs.append({'type': "UserCreateDatabaseFlag", 'value': config.get("Database", "create_database")}) inputs.append({'type': "ExecuteMapping", 'value': config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping")}) inputs.append({'type': "DatabaseSocketAddresses", 'value': self._database_socket_addresses}) inputs.append({'type': "SendStartNotifications", 'value': config.getboolean("Database", "send_start_notification")}) inputs.append({'type': "ProvenanceFilePath", 'value': provenance_file_path}) # add paths for each file based version inputs.append({'type': "FileCoreAllocationsFilePath", 'value': os.path.join( json_folder, "core_allocations.json")}) inputs.append({'type': "FileSDRAMAllocationsFilePath", 'value': os.path.join( json_folder, "sdram_allocations.json")}) inputs.append({'type': "FileMachineFilePath", 'value': os.path.join( json_folder, "machine.json")}) inputs.append({'type': "FilePartitionedGraphFilePath", 'value': os.path.join( json_folder, "partitioned_graph.json")}) inputs.append({'type': "FilePlacementFilePath", 'value': os.path.join( json_folder, "placements.json")}) inputs.append({'type': "FileRouingPathsFilePath", 'value': os.path.join( json_folder, "routing_paths.json")}) inputs.append({'type': "FileConstraintsFilePath", 'value': os.path.join( json_folder, "constraints.json")}) return inputs def _calculate_number_of_machine_time_steps(self, run_time): if run_time is not None: self._no_machine_time_steps =\ int((run_time * 1000.0) / self._machine_time_step) ceiled_machine_time_steps = \ math.ceil((run_time * 1000.0) / self._machine_time_step) if self._no_machine_time_steps != ceiled_machine_time_steps: logger.warn( "The runtime and machine time step combination result in " "a fractional number of machine time steps") self._no_machine_time_steps = int(ceiled_machine_time_steps) for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractDataSpecableVertex): vertex.set_no_machine_time_steps( self._no_machine_time_steps) else: self._no_machine_time_steps = None logger.warn("You have set a runtime that will never end, this may" "cause the neural models to fail to partition " "correctly") for vertex in self._partitionable_graph.vertices: if ((isinstance(vertex, AbstractSpikeRecordable) and vertex.is_recording_spikes()) or (isinstance(vertex, AbstractVRecordable) and vertex.is_recording_v()) or (isinstance(vertex, AbstractGSynRecordable) and vertex.is_recording_gsyn)): raise common_exceptions.ConfigurationException( "recording a population when set to infinite runtime " "is not currently supportable in this tool chain." "watch this space") @property def app_id(self): """ :return: """ return self._app_id @property def has_ran(self): """ :return: """ return self._has_ran @property def machine_time_step(self): """ :return: """ return self._machine_time_step @property def no_machine_time_steps(self): """ :return: """ return self._no_machine_time_steps @property def timescale_factor(self): """ :return: """ return self._time_scale_factor @property def spikes_per_second(self): """ :return: """ return self._spikes_per_second @property def ring_buffer_sigma(self): """ :return: """ return self._ring_buffer_sigma @property def get_multi_cast_source(self): """ :return: """ return self._multi_cast_vertex @property def partitioned_graph(self): """ :return: """ return self._partitioned_graph @property def partitionable_graph(self): """ :return: """ return self._partitionable_graph @property def placements(self): """ :return: """ return self._placements @property def transceiver(self): """ :return: """ return self._txrx @property def graph_mapper(self): """ :return: """ return self._graph_mapper @property def routing_infos(self): """ :return: """ return self._routing_infos @property def min_supported_delay(self): """ The minimum supported delay based in milliseconds :return: """ return self._min_supported_delay @property def max_supported_delay(self): """ The maximum supported delay based in milliseconds :return: """ return self._max_supported_delay def set_app_id(self, value): """ :param value: :return: """ self._app_id = value def get_current_time(self): """ :return: """ if self._has_ran: return float(self._runtime) return 0.0 def __repr__(self): return "Spinnaker object for machine {}".format(self._hostname) def add_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge( self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_edge(edge) # add any dependent edges and vertices if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_edge( dependant_edge, vertex_to_add.edge_partition_identifier_for_dependent_edge) def add_edge(self, edge_to_add, partition_identifier=None): """ :param edge_to_add: :param partition_identifier: the partition identifier for the outgoing\ edge partition :return: """ self._partitionable_graph.add_edge(edge_to_add, partition_identifier) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population( size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def create_projection( self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: :param postsynaptic_population: :param connector: :param source: :param target: :param synapse_dynamics: :param label: :param rng: :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection( presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor, user_max_delay=self.max_supported_delay) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None): """ :param turn_off_machine: decides if the machine should be powered down\ after running the execution. Note that this powers down all boards\ connected to the BMP connections given to the transceiver :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :return: None """ for population in self._populations: population._end() # if not a virtual machine, then shut down stuff on the board if not config.getboolean("Machine", "virtual_board"): if turn_off_machine is None: turn_off_machine = \ config.getboolean("Machine", "turn_off_machine") if clear_routing_tables is None: clear_routing_tables = config.getboolean( "Machine", "clear_routing_tables") if clear_tags is None: clear_tags = config.getboolean("Machine", "clear_tags") # if stopping on machine, clear iptags and if clear_tags: for ip_tag in self._tags.ip_tags: self._txrx.clear_ip_tag( ip_tag.tag, board_address=ip_tag.board_address) for reverse_ip_tag in self._tags.reverse_ip_tags: self._txrx.clear_ip_tag( reverse_ip_tag.tag, board_address=reverse_ip_tag.board_address) # if clearing routing table entries, clear if clear_routing_tables: for router_table in self._router_tables.routing_tables: if not self._machine.get_chip_at(router_table.x, router_table.y).virtual: self._txrx.clear_multicast_routes(router_table.x, router_table.y) # execute app stop # self._txrx.stop_application(self._app_id) if self._create_database: self._database_interface.stop() # stop the transceiver if turn_off_machine: logger.info("Turning off machine") self._txrx.close(power_off_machine=turn_off_machine) def _add_socket_address(self, socket_address): """ :param socket_address: :return: """ self._database_socket_addresses.add(socket_address)
class Spinnaker(FrontEndCommonConfigurationFunctions, FrontEndCommonInterfaceFunctions, FrontEndCommonProvenanceFunctions, SpynnakerConfigurationFunctions): """ Spinnaker """ def __init__(self, host_name=None, timestep=None, min_delay=None, max_delay=None, graph_label=None, database_socket_addresses=None): FrontEndCommonConfigurationFunctions.__init__(self, host_name, graph_label) SpynnakerConfigurationFunctions.__init__(self) FrontEndCommonProvenanceFunctions.__init__(self) self._database_socket_addresses = set() self._database_interface = None self._create_database = None self._populations = list() if self._app_id is None: self._set_up_main_objects( app_id=config.getint("Machine", "appID"), execute_data_spec_report=config.getboolean( "Reports", "writeTextSpecs"), execute_partitioner_report=config.getboolean( "Reports", "writePartitionerReports"), execute_placer_report=config.getboolean( "Reports", "writePlacerReports"), execute_router_dat_based_report=config.getboolean( "Reports", "writeRouterDatReport"), reports_are_enabled=config.getboolean("Reports", "reportsEnabled"), generate_performance_measurements=config.getboolean( "Reports", "outputTimesForSections"), execute_router_report=config.getboolean( "Reports", "writeRouterReports"), execute_write_reload_steps=config.getboolean( "Reports", "writeReloadSteps"), generate_transciever_report=config.getboolean( "Reports", "writeTransceiverReport"), execute_routing_info_report=config.getboolean( "Reports", "writeRouterInfoReport"), in_debug_mode=config.get("Mode", "mode") == "Debug", generate_tag_report=config.getboolean( "Reports", "writeTagAllocationReports")) self._set_up_pacman_algorthms_listings( partitioner_algorithm=config.get("Partitioner", "algorithm"), placer_algorithm=config.get("Placer", "algorithm"), key_allocator_algorithm=config.get("KeyAllocator", "algorithm"), routing_algorithm=config.get("Routing", "algorithm")) # set up exeuctable specifics self._set_up_executable_specifics() self._set_up_report_specifics( default_report_file_path=config.get("Reports", "defaultReportFilePath"), max_reports_kept=config.getint("Reports", "max_reports_kept"), reports_are_enabled=config.getboolean("Reports", "reportsEnabled"), write_provance_data=config.getboolean("Reports", "writeProvanceData"), write_text_specs=config.getboolean("Reports", "writeTextSpecs")) self._set_up_output_application_data_specifics( max_application_binaries_kept=config.getint( "Reports", "max_application_binaries_kept"), where_to_write_application_data_files=config.get( "Reports", "defaultApplicationDataFilePath")) # set up spynnaker specifics, such as setting the machineName from conf self._set_up_machine_specifics(timestep, min_delay, max_delay, host_name) self._spikes_per_second = float( config.getfloat("Simulation", "spikes_per_second")) self._ring_buffer_sigma = float( config.getfloat("Simulation", "ring_buffer_sigma")) # Determine default executable folder location # and add this default to end of list of search paths executable_finder.add_path(os.path.dirname(model_binaries.__file__)) FrontEndCommonInterfaceFunctions.__init__( self, self._reports_states, self._report_default_directory, self._app_data_runtime_folder) logger.info("Setting time scale factor to {}.".format( self._time_scale_factor)) logger.info("Setting appID to %d." % self._app_id) # get the machine time step logger.info("Setting machine time step to {} micro-seconds.".format( self._machine_time_step)) self._edge_count = 0 # Manager of buffered sending self._send_buffer_manager = None def run(self, run_time): """ :param run_time: :return: """ # sort out config param to be valid types width = config.get("Machine", "width") height = config.get("Machine", "height") if width == "None": width = None else: width = int(width) if height == "None": height = None else: height = int(height) number_of_boards = config.get("Machine", "number_of_boards") if number_of_boards == "None": number_of_boards = None self.setup_interfaces( hostname=self._hostname, bmp_details=config.get("Machine", "bmp_names"), downed_chips=config.get("Machine", "down_chips"), downed_cores=config.get("Machine", "down_cores"), board_version=config.getint("Machine", "version"), number_of_boards=number_of_boards, width=width, height=height, is_virtual=config.getboolean("Machine", "virtual_board"), virtual_has_wrap_arounds=config.getboolean( "Machine", "requires_wrap_arounds"), auto_detect_bmp=config.getboolean("Machine", "auto_detect_bmp")) # adds extra stuff needed by the reload script which cannot be given # directly. if self._reports_states.transciever_report: self._reload_script.runtime = run_time self._reload_script.time_scale_factor = self._time_scale_factor # create network report if needed if self._reports_states is not None: reports.network_specification_partitionable_report( self._report_default_directory, self._partitionable_graph, self._hostname) # calculate number of machine time steps if run_time is not None: self._no_machine_time_steps =\ int((run_time * 1000.0) / self._machine_time_step) ceiled_machine_time_steps = \ math.ceil((run_time * 1000.0) / self._machine_time_step) if self._no_machine_time_steps != ceiled_machine_time_steps: raise common_exceptions.ConfigurationException( "The runtime and machine time step combination result in " "a factional number of machine runable time steps and " "therefore spinnaker cannot determine how many to run for") for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractDataSpecableVertex): vertex.set_no_machine_time_steps( self._no_machine_time_steps) else: self._no_machine_time_steps = None logger.warn("You have set a runtime that will never end, this may" "cause the neural models to fail to partition " "correctly") for vertex in self._partitionable_graph.vertices: if (isinstance(vertex, AbstractPopulationRecordableVertex) and vertex.record): raise common_exceptions.ConfigurationException( "recording a population when set to infinite runtime " "is not currently supportable in this tool chain." "watch this space") do_timing = config.getboolean("Reports", "outputTimesForSections") if do_timing: timer = Timer() else: timer = None self.set_runtime(run_time) logger.info("*** Running Mapper *** ") if do_timing: timer.start_timing() self.map_model() if do_timing: timer.take_sample() # add database generation if requested needs_database = self._auto_detect_database(self._partitioned_graph) user_create_database = config.get("Database", "create_database") if ((user_create_database == "None" and needs_database) or user_create_database == "True"): wait_on_confirmation = config.getboolean("Database", "wait_on_confirmation") self._database_interface = SpynnakerDataBaseInterface( self._app_data_runtime_folder, wait_on_confirmation, self._database_socket_addresses) self._database_interface.add_system_params(self._time_scale_factor, self._machine_time_step, self._runtime) self._database_interface.add_machine_objects(self._machine) self._database_interface.add_partitionable_vertices( self._partitionable_graph) self._database_interface.add_partitioned_vertices( self._partitioned_graph, self._graph_mapper, self._partitionable_graph) self._database_interface.add_placements(self._placements, self._partitioned_graph) self._database_interface.add_routing_infos(self._routing_infos, self._partitioned_graph) self._database_interface.add_routing_tables(self._router_tables) self._database_interface.add_tags(self._partitioned_graph, self._tags) execute_mapping = config.getboolean( "Database", "create_routing_info_to_neuron_id_mapping") if execute_mapping: self._database_interface.create_neuron_to_key_mapping( graph_mapper=self._graph_mapper, partitionable_graph=self._partitionable_graph, partitioned_graph=self._partitioned_graph, routing_infos=self._routing_infos) # if using a reload script, add if that needs to wait for # confirmation if self._reports_states.transciever_report: self._reload_script.wait_on_confirmation = wait_on_confirmation for socket_address in self._database_socket_addresses: self._reload_script.add_socket_address(socket_address) self._database_interface.send_read_notification() # execute data spec generation if do_timing: timer.start_timing() logger.info("*** Generating Output *** ") logger.debug("") executable_targets = self.generate_data_specifications() if do_timing: timer.take_sample() # execute data spec execution if do_timing: timer.start_timing() processor_to_app_data_base_address = \ self.execute_data_specification_execution( config.getboolean("SpecExecution", "specExecOnHost"), self._hostname, self._placements, self._graph_mapper, write_text_specs=config.getboolean( "Reports", "writeTextSpecs"), runtime_application_data_folder=self._app_data_runtime_folder, machine=self._machine) if self._reports_states is not None: reports.write_memory_map_report( self._report_default_directory, processor_to_app_data_base_address) if do_timing: timer.take_sample() if (not isinstance(self._machine, VirtualMachine) and config.getboolean("Execute", "run_simulation")): if do_timing: timer.start_timing() logger.info("*** Loading tags ***") self.load_tags(self._tags) if self._do_load is True: logger.info("*** Loading data ***") self._load_application_data( self._placements, self._graph_mapper, processor_to_app_data_base_address, self._hostname, app_data_folder=self._app_data_runtime_folder, verify=config.getboolean("Mode", "verify_writes")) self.load_routing_tables(self._router_tables, self._app_id) logger.info("*** Loading executables ***") self.load_executable_images(executable_targets, self._app_id) logger.info("*** Loading buffers ***") self.set_up_send_buffering(self._partitioned_graph, self._placements, self._tags) # end of entire loading setup if do_timing: timer.take_sample() if self._do_run is True: logger.info("*** Running simulation... *** ") if do_timing: timer.start_timing() # every thing is in sync0. load the initial buffers self._send_buffer_manager.load_initial_buffers() if do_timing: timer.take_sample() wait_on_confirmation = config.getboolean( "Database", "wait_on_confirmation") send_start_notification = config.getboolean( "Database", "send_start_notification") self.wait_for_cores_to_be_ready(executable_targets, self._app_id) # wait till external app is ready for us to start if required if (self._database_interface is not None and wait_on_confirmation): self._database_interface.wait_for_confirmation() self.start_all_cores(executable_targets, self._app_id) if (self._database_interface is not None and send_start_notification): self._database_interface.send_start_notification() if self._runtime is None: logger.info("Application is set to run forever - exiting") else: self.wait_for_execution_to_complete( executable_targets, self._app_id, self._runtime, self._time_scale_factor) self._has_ran = True if self._retrieve_provance_data: progress = ProgressBar(self._placements.n_placements + 1, "getting provenance data") # retrieve provence data from central file_path = os.path.join(self._report_default_directory, "provance_data") # check the directory doesnt already exist if not os.path.exists(file_path): os.mkdir(file_path) # write provanence data self.write_provenance_data_in_xml(file_path, self._txrx) progress.update() # retrieve provenance data from any cores that provide data for placement in self._placements.placements: if isinstance(placement.subvertex, AbstractProvidesProvenanceData): core_file_path = os.path.join( file_path, "Provanence_data_for_{}_{}_{}_{}.xml".format( placement.subvertex.label, placement.x, placement.y, placement.p)) placement.subvertex.write_provenance_data_in_xml( core_file_path, self.transceiver, placement) progress.update() progress.end() elif isinstance(self._machine, VirtualMachine): logger.info( "*** Using a Virtual Machine so no simulation will occur") else: logger.info("*** No simulation requested: Stopping. ***") @property def app_id(self): """ :return: """ return self._app_id @property def has_ran(self): """ :return: """ return self._has_ran @property def machine_time_step(self): """ :return: """ return self._machine_time_step @property def no_machine_time_steps(self): """ :return: """ return self._no_machine_time_steps @property def timescale_factor(self): """ :return: """ return self._time_scale_factor @property def spikes_per_second(self): """ :return: """ return self._spikes_per_second @property def ring_buffer_sigma(self): """ :return: """ return self._ring_buffer_sigma @property def get_multi_cast_source(self): """ :return: """ return self._multi_cast_vertex @property def partitioned_graph(self): """ :return: """ return self._partitioned_graph @property def partitionable_graph(self): """ :return: """ return self._partitionable_graph @property def placements(self): """ :return: """ return self._placements @property def transceiver(self): """ :return: """ return self._txrx @property def graph_mapper(self): """ :return: """ return self._graph_mapper @property def routing_infos(self): """ :return: """ return self._routing_infos def set_app_id(self, value): """ :param value: :return: """ self._app_id = value def get_current_time(self): """ :return: """ if self._has_ran: return float(self._runtime) return 0.0 def __repr__(self): return "Spinnaker object for machine {}".format(self._hostname) def map_model(self): """ executes the pacman compilation stack """ pacman_report_state = \ self._reports_states.generate_pacman_report_states() self._add_virtual_chips() # execute partitioner self._execute_partitioner(pacman_report_state) # execute placer self._execute_placer(pacman_report_state) # exeucte tag allocator self._execute_tag_allocator(pacman_report_state) # execute pynn subedge pruning self._partitioned_graph, self._graph_mapper = \ GraphEdgeFilter(self._report_default_directory)\ .run(self._partitioned_graph, self._graph_mapper) # execute key allocator self._execute_key_allocator(pacman_report_state) # execute router self._execute_router(pacman_report_state) def _execute_tag_allocator(self, pacman_report_state): """ :param pacman_report_state: :return: """ if self._tag_allocator_algorithm is None: self._tag_allocator_algorithm = BasicTagAllocator() else: self._tag_allocator_algorithm = self._tag_allocator_algorithm() # execute tag allocation self._tags = self._tag_allocator_algorithm.allocate_tags( self._machine, self._placements) # generate reports if (pacman_report_state is not None and pacman_report_state.tag_allocation_report): pacman_reports.tag_allocator_report(self._report_default_directory, self._tags) def _execute_key_allocator(self, pacman_report_state): """ executes the key allocator :param pacman_report_state: :return: """ if self._key_allocator_algorithm is None: self._key_allocator_algorithm = BasicRoutingInfoAllocator() else: self._key_allocator_algorithm = self._key_allocator_algorithm() # execute routing info generator # Generate an n_keys map for the graph and add constraints n_keys_map = DictBasedPartitionedEdgeNKeysMap() for edge in self._partitioned_graph.subedges: vertex_slice = self._graph_mapper.get_subvertex_slice( edge.pre_subvertex) super_edge = (self._graph_mapper. get_partitionable_edge_from_partitioned_edge(edge)) if not isinstance(super_edge.pre_vertex, AbstractProvidesNKeysForEdge): n_keys_map.set_n_keys_for_patitioned_edge( edge, vertex_slice.n_atoms) else: n_keys_map.set_n_keys_for_patitioned_edge( edge, super_edge.pre_vertex.get_n_keys_for_partitioned_edge( edge, self._graph_mapper)) if isinstance(super_edge.pre_vertex, AbstractProvidesOutgoingEdgeConstraints): edge.add_constraints( super_edge.pre_vertex.get_outgoing_edge_constraints( edge, self._graph_mapper)) if isinstance(super_edge.post_vertex, AbstractProvidesIncomingEdgeConstraints): edge.add_constraints( super_edge.post_vertex.get_incoming_edge_constraints( edge, self._graph_mapper)) # execute routing info generator self._routing_infos = \ self._key_allocator_algorithm.allocate_routing_info( self._partitioned_graph, self._placements, n_keys_map) # generate reports if (pacman_report_state is not None and pacman_report_state.routing_info_report): pacman_reports.routing_info_reports(self._report_default_directory, self._partitioned_graph, self._routing_infos) def _execute_router(self, pacman_report_state): """ exectes the router algorithum :param pacman_report_state: :return: """ # set up a default placer algorithm if none are specified if self._router_algorithm is None: self._router_algorithm = BasicDijkstraRouting() else: self._router_algorithm = self._router_algorithm() self._router_tables = \ self._router_algorithm.route( self._routing_infos, self._placements, self._machine, self._partitioned_graph) if pacman_report_state is not None and \ pacman_report_state.router_report: pacman_reports.router_reports( graph=self._partitionable_graph, hostname=self._hostname, graph_to_sub_graph_mapper=self._graph_mapper, placements=self._placements, report_folder=self._report_default_directory, include_dat_based=pacman_report_state.router_dat_based_report, routing_tables=self._router_tables, routing_info=self._routing_infos, machine=self._machine) if self._in_debug_mode: # check that all routes are valid and no cycles exist valid_route_checker = ValidRouteChecker( placements=self._placements, routing_infos=self._routing_infos, routing_tables=self._router_tables, machine=self._machine, partitioned_graph=self._partitioned_graph) valid_route_checker.validate_routes() def _execute_partitioner(self, pacman_report_state): """ executes the partitioner function :param pacman_report_state: :return: """ # execute partitioner or default partitioner (as seen fit) if self._partitioner_algorithm is None: self._partitioner_algorithm = BasicPartitioner() else: self._partitioner_algorithm = self._partitioner_algorithm() # execute partitioner self._partitioned_graph, self._graph_mapper = \ self._partitioner_algorithm.partition(self._partitionable_graph, self._machine) # execute reports if (pacman_report_state is not None and pacman_report_state.partitioner_report): pacman_reports.partitioner_reports(self._report_default_directory, self._hostname, self._partitionable_graph, self._graph_mapper) def _execute_placer(self, pacman_report_state): """ executes the placer :param pacman_report_state: :return: """ # execute placer or default placer (as seen fit) if self._placer_algorithm is None: self._placer_algorithm = BasicPlacer() else: self._placer_algorithm = self._placer_algorithm() # execute placer self._placements = self._placer_algorithm.place( self._partitioned_graph, self._machine) # execute placer reports if needed if (pacman_report_state is not None and pacman_report_state.placer_report): pacman_reports.placer_reports_with_partitionable_graph( graph=self._partitionable_graph, graph_mapper=self._graph_mapper, hostname=self._hostname, machine=self._machine, placements=self._placements, report_folder=self._report_default_directory) def generate_data_specifications(self): """ generates the dsg for the graph. :return: """ # iterate though subvertexes and call generate_data_spec for each # vertex executable_targets = ExecutableTargets() # create a progress bar for end users progress_bar = ProgressBar(len(list(self._placements.placements)), "on generating data specifications") for placement in self._placements.placements: associated_vertex =\ self._graph_mapper.get_vertex_from_subvertex( placement.subvertex) # if the vertex can generate a DSG, call it if isinstance(associated_vertex, AbstractDataSpecableVertex): ip_tags = self._tags.get_ip_tags_for_vertex( placement.subvertex) reverse_ip_tags = self._tags.get_reverse_ip_tags_for_vertex( placement.subvertex) associated_vertex.generate_data_spec( placement.subvertex, placement, self._partitioned_graph, self._partitionable_graph, self._routing_infos, self._hostname, self._graph_mapper, self._report_default_directory, ip_tags, reverse_ip_tags, self._writeTextSpecs, self._app_data_runtime_folder) progress_bar.update() # Get name of binary from vertex binary_name = associated_vertex.get_binary_file_name() # Attempt to find this within search paths binary_path = executable_finder.get_executable_path( binary_name) if binary_path is None: raise exceptions.ExecutableNotFoundException(binary_name) if not executable_targets.has_binary(binary_path): executable_targets.add_binary(binary_path) executable_targets.add_processor(binary_path, placement.x, placement.y, placement.p) # finish the progress bar progress_bar.end() return executable_targets def add_vertex(self, vertex_to_add): """ :param vertex_to_add: :return: """ if isinstance(vertex_to_add, CommandSender): self._multi_cast_vertex = vertex_to_add self._partitionable_graph.add_vertex(vertex_to_add) if isinstance(vertex_to_add, AbstractSendMeMulticastCommandsVertex): if self._multi_cast_vertex is None: self._multi_cast_vertex = CommandSender( self._machine_time_step, self._time_scale_factor) self.add_vertex(self._multi_cast_vertex) edge = MultiCastPartitionableEdge(self._multi_cast_vertex, vertex_to_add) self._multi_cast_vertex.add_commands(vertex_to_add.commands, edge) self.add_edge(edge) # add any dependent edges and verts if needed if isinstance(vertex_to_add, AbstractVertexWithEdgeToDependentVertices): for dependant_vertex in vertex_to_add.dependent_vertices: self.add_vertex(dependant_vertex) dependant_edge = MultiCastPartitionableEdge( pre_vertex=vertex_to_add, post_vertex=dependant_vertex) self.add_edge(dependant_edge) def add_edge(self, edge_to_add): """ :param edge_to_add: :return: """ self._partitionable_graph.add_edge(edge_to_add) def create_population(self, size, cellclass, cellparams, structure, label): """ :param size: :param cellclass: :param cellparams: :param structure: :param label: :return: """ return Population(size=size, cellclass=cellclass, cellparams=cellparams, structure=structure, label=label, spinnaker=self) def _add_population(self, population): """ Called by each population to add itself to the list """ self._populations.append(population) def create_projection(self, presynaptic_population, postsynaptic_population, connector, source, target, synapse_dynamics, label, rng): """ :param presynaptic_population: :param postsynaptic_population: :param connector: :param source: :param target: :param synapse_dynamics: :param label: :param rng: :return: """ if label is None: label = "Projection {}".format(self._edge_count) self._edge_count += 1 return Projection(presynaptic_population=presynaptic_population, label=label, postsynaptic_population=postsynaptic_population, rng=rng, connector=connector, source=source, target=target, synapse_dynamics=synapse_dynamics, spinnaker_control=self, machine_time_step=self._machine_time_step, timescale_factor=self._time_scale_factor) def _add_virtual_chips(self): for vertex in self._partitionable_graph.vertices: if isinstance(vertex, AbstractVirtualVertex): # check if the virtual chip doesn't already exist if self._machine.get_chip_at(vertex.virtual_chip_x, vertex.virtual_chip_y) is None: virutal_chip = self._create_virtual_chip(vertex) self._machine.add_chip(virutal_chip) def _create_virtual_chip(self, virtual_vertex): sdram_object = SDRAM() # creates the two links spinnaker_link_id = virtual_vertex.get_spinnaker_link_id spinnaker_link_data = \ self._machine.locate_connected_chips_coords_and_link( config.getint("Machine", "version"), spinnaker_link_id) virtual_link_id = (spinnaker_link_data.connected_link + 3) % 6 to_virtual_chip_link = Link( destination_x=virtual_vertex.virtual_chip_x, destination_y=virtual_vertex.virtual_chip_y, source_x=spinnaker_link_data.connected_chip_x, source_y=spinnaker_link_data.connected_chip_y, multicast_default_from=virtual_link_id, multicast_default_to=virtual_link_id, source_link_id=spinnaker_link_data.connected_link) from_virtual_chip_link = Link( destination_x=spinnaker_link_data.connected_chip_x, destination_y=spinnaker_link_data.connected_chip_y, source_x=virtual_vertex.virtual_chip_x, source_y=virtual_vertex.virtual_chip_y, multicast_default_from=(spinnaker_link_data.connected_link), multicast_default_to=spinnaker_link_data.connected_link, source_link_id=virtual_link_id) # create the router links = [from_virtual_chip_link] router_object = MachineRouter( links=links, emergency_routing_enabled=False, clock_speed=MachineRouter.ROUTER_DEFAULT_CLOCK_SPEED, n_available_multicast_entries=sys.maxint) # create the processors processors = list() for virtual_core_id in range(0, 128): processors.append( Processor(virtual_core_id, Processor.CPU_AVAILABLE, virtual_core_id == 0)) # connect the real chip with the virtual one connected_chip = self._machine.get_chip_at( spinnaker_link_data.connected_chip_x, spinnaker_link_data.connected_chip_y) connected_chip.router.add_link(to_virtual_chip_link) # return new v chip return Chip(processors=processors, router=router_object, sdram=sdram_object, x=virtual_vertex.virtual_chip_x, y=virtual_vertex.virtual_chip_y, virtual=True, nearest_ethernet_x=None, nearest_ethernet_y=None) def stop(self, turn_off_machine=None, clear_routing_tables=None, clear_tags=None): """ :param turn_off_machine: decides if the machine should be powered down\ after running the exeuction. Note that this powers down all boards\ connected to the BMP connections given to the transciever :type turn_off_machine: bool :param clear_routing_tables: informs the tool chain if it\ should turn off the clearing of the routing tables :type clear_routing_tables: bool :param clear_tags: informs the tool chain if it should clear the tags\ off the machine at stop :type clear_tags: boolean :return: None """ for population in self._populations: population._end() if turn_off_machine is None: config.getboolean("Machine", "turn_off_machine") if clear_routing_tables is None: config.getboolean("Machine", "clear_routing_tables") if clear_tags is None: config.getboolean("Machine", "clear_tags") # if stopping on machine, clear iptags and if clear_tags: for ip_tag in self._tags.ip_tags: self._txrx.clear_ip_tag(ip_tag.tag, board_address=ip_tag.board_address) for reverse_ip_tag in self._tags.reverse_ip_tags: self._txrx.clear_ip_tag( reverse_ip_tag.tag, board_address=reverse_ip_tag.board_address) # if clearing routing table entries, clear if clear_routing_tables: for router_table in self._router_tables.routing_tables: if not self._machine.get_chip_at(router_table.x, router_table.y).virtual: self._txrx.clear_multicast_routes(router_table.x, router_table.y) # execute app stop # self._txrx.stop_application(self._app_id) if self._create_database: self._database_interface.stop() # if asked to turn off machine, power down each rack via bmp # connections if turn_off_machine: self._txrx.power_off_machine() # stop the transciever self._txrx.close() def _add_socket_address(self, socket_address): """ :param socket_address: :return: """ self._database_socket_addresses.add(socket_address)