
    c&                     F   d Z ddlZddlZddlZddlZddlZddlZddlmZ ddl	Z	ddl
mZ  ej        e          ZdZdZ G d d          Zed	k    r ej        d
ej                    ej        e dd         ej                  Ze                    ddede           e                                Ze                    dd                    ej                              ej        d eej                             e                    dej                    dS dS )a  Dispatcher process which orchestrates distributed :class:`~gensim.models.lsimodel.LsiModel` computations.
Run this script only once, on any node in your cluster.

Notes
-----
The dispatcher expects to find worker scripts already running. Make sure you run as many workers as you like on
your machines **before** launching the dispatcher.


How to use distributed LSI
--------------------------

#. Install needed dependencies (Pyro4) ::

    pip install gensim[distributed]

#. Setup serialization (on each machine) ::

    export PYRO_SERIALIZERS_ACCEPTED=pickle
    export PYRO_SERIALIZER=pickle

#. Run nameserver ::

    python -m Pyro4.naming -n 0.0.0.0 &

#. Run workers (on each machine) ::

    python -m gensim.models.lsi_worker &

#. Run dispatcher ::

    python -m gensim.models.lsi_dispatcher &

#. Run :class:`~gensim.models.lsimodel.LsiModel` in distributed mode:

    .. sourcecode:: pycon

        >>> from gensim.test.utils import common_corpus, common_dictionary
        >>> from gensim.models import LsiModel
        >>>
        >>> model = LsiModel(common_corpus, id2word=common_dictionary, distributed=True)

Command line arguments
----------------------

.. program-output:: python -m gensim.models.lsi_dispatcher --help
   :ellipsis: 0, -5

    N)Queue)utils
   i3c                   f   e Zd ZdZddZej        d             Zej        d             Zej        d             Z	ej        d             Z
ej        d             Zej        d	             Zej        ej         ej        d
          d                                     Zd Zej        d             ZdS )
DispatcherzDispatcher object that communicates and coordinates individual workers.

    Warnings
    --------
    There should never be more than one dispatcher running at any one time.

    r   c                 0    || _         i | _        d| _        dS )aZ  Partly initialize the dispatcher.

        A full initialization (including initialization of the workers) requires a call to
        :meth:`~gensim.models.lsi_dispatcher.Dispatcher.initialize`

        Parameters
        ----------
        maxsize : int, optional
            Maximum number of jobs to be kept pre-fetched in the queue.

        N)maxsizeworkerscallback)selfr	   s     <lib/python3.11/site-packages/gensim/models/lsi_dispatcher.py__init__zDispatcher.__init__\   s         c                    t          | j                  | _        t          j                    | _        d| _        d| _        i | _        t          j
                    5 }t          j        d          | _        |                    d                                          D ]\  }}	 t          j        |          }t!          | j                  }t"                              d||            |j        |fd| j        i| || j        |<   j# t          j        j        $ r3 t"                              d|           |                    |           Y w xY w	 d	d	d	           n# 1 swxY w Y   | j        st1          d
          d	S )a  Fully initialize the dispatcher and all its workers.

        Parameters
        ----------
        **model_params
            Keyword parameters used to initialize individual workers
            (gets handed all the way down to :meth:`gensim.models.lsi_worker.Worker.initialize`).
            See :class:`~gensim.models.lsimodel.LsiModel`.

        Raises
        ------
        RuntimeError
            When no workers are found (the :mod:`gensim.model.lsi_worker` script must be ran beforehand).

        r	   r   zPYRONAME:gensim.lsi_dispatcherzgensim.lsi_worker)prefixzregistering worker #%i from %s
dispatcherz;unresponsive worker at %s, deleting it from the name serverNzEno workers found; run some lsi_worker scripts on your machines first!)r   r	   jobs	threadingLocklock_update	_jobsdone_jobsreceivedr
   r   getNSPyro4Proxyr   listitemslenloggerinfo
initializeerrors	PyroError	exceptionremoveRuntimeError)r   model_paramsnsnameuriworkerworkerids          r   r"   zDispatcher.initializel   s   " $,///	$>++ []] 	$b!K(HIIDMWW,?W@@FFHH 
$ 
$	c	$"[--F"4<00HKK @(CPPP%F%hYY4=YLYYY-3DL**|- $ $ $$$%bdghhhIIdOOOOO$
$	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ 	$ | 	hfggg	h 	hs9   AE#A#DEAEEEEE"%E"c                 H    d | j                                         D             S )zGet pyro URIs of all registered workers.

        Returns
        -------
        list of URIs
            The pyro URIs for each worker.

        c                     g | ]	}|j         
S  )_pyroUri).0r,   s     r   
<listcomp>z)Dispatcher.getworkers.<locals>.<listcomp>   s    DDDFDDDr   )r
   valuesr   s    r   
getworkerszDispatcher.getworkers   s'     EDdl.A.A.C.CDDDDr   c                     t                               d|           | j                            dd          }t                               d|| j                                                   |S )a  Atomically pop a job from the queue.

        Parameters
        ----------
        worker_id : int
            The worker that requested the job.

        Returns
        -------
        iterable of iterable of (int, float)
            The corpus in BoW format.

        zworker #%i requesting a new jobT   blocktimeoutz"worker #%i got a new job (%i left))r    r!   r   getqsize)r   	worker_idjobs      r   getjobzDispatcher.getjob   sX     	5yAAAimm$m228)TY__EVEVWWW
r   c                     | xj         dz  c_         | j                            |dt                     t                              d| j                                                   dS )zAtomically add a job to the queue.

        Parameters
        ----------
        job : iterable of list of (int, float)
            The corpus in BoW format.

        r8   Tr9   z%added a new job (len(queue)=%i items)N)r   r   putHUGE_TIMEOUTr    r!   r=   )r   r?   s     r   putjobzDispatcher.putjob   sY     	a	c|<<<;TY__=N=NOOOOOr   c                    t                               d           t                               d| j        | j                   | j        | j        k     r$t          j        d           | j        | j        k     $t                               dt          | j                             t          | j        
                                          }|d         d                                         }|dd         D ]G\  }}t                               d|           |                    |                                           Ht                               d	           |S )
zMerge projections from across all workers and get the final projection.

        Returns
        -------
        :class:`~gensim.models.lsimodel.Projection`
            The current projection of the total model.

        z*end of input, assigning all remaining jobsz jobs done: %s, jobs received: %sg      ?zmerging states from %i workersr   r8   Nzpulling state from worker %szsending out merged projection)r    r!   debugr   r   timesleepr   r
   r   r   getstatemerge)r   r
   resultr-   r,   s        r   rI   zDispatcher.getstate   s#    	@AAA7I[\\\nt11 	JsOOO nt11 	 	4c$,6G6GHHHt|))++,,A'')) ' 	, 	,HfKK6AAALL**++++3444r   c                     | j                                         D ]H\  }}t                              d|           |                                 |                                 Id| _        d| _        dS )z2Re-initialize all workers for a new decomposition.zresetting worker %sr   N)r
   r   r    r!   reset
requestjobr   r   r   r-   r,   s      r   rM   zDispatcher.reset   sr     !% 2 2 4 4 	  	 HfKK-x888LLNNNr   r   c                     | xj         dz  c_         t                              d|| j                    | j        |         }|                                 dS )a  A worker has finished its job. Log this event and then asynchronously transfer control back to the worker.

        Callback used by workers to notify when their job is done.

        The job done event is logged and then control is asynchronously transfered back to the worker
        (who can then request another job). In this way, control flow basically oscillates between
        :meth:`gensim.models.lsi_dispatcher.Dispatcher.jobdone` and :meth:`gensim.models.lsi_worker.Worker.requestjob`.

        Parameters
        ----------
        workerid : int
            The ID of the worker that finished the job (used for logging).

        r8   zworker #%s finished job #%iN)r   r    r!   r
   rN   rO   s      r   jobdonezDispatcher.jobdone   sQ    $ 	!18T^LLLh'r   c                     | j         S )zWrap :attr:`~gensim.models.lsi_dispatcher.Dispatcher._jobsdone`, needed for remote access through proxies.

        Returns
        -------
        int
            Number of jobs already completed.

        )r   r5   s    r   jobsdonezDispatcher.jobsdone   s     ~r   c                     | j                                         D ]4\  }}t                              d|           |                                 5t                              d           t          j        d           dS )z9Terminate all registered workers and then the dispatcher.zterminating worker %szterminating dispatcherr   N)r
   r   r    r!   exitos_exitrO   s      r   rU   zDispatcher.exit  sn     !% 2 2 4 4 	 	HfKK/:::KKMMMM,---
r   N)r   )__name__
__module____qualname____doc__r   r   exposer"   r6   r@   rD   rI   rM   onewayr   synchronousrQ   rS   rU   r0   r   r   r   r   T   sW             \&h &h \&hP \	E 	E \	E \  \& \P P \P \  \6 \  \ \
\U}%%  &% \ \(	 	 	 \  \  r   r   __main__z)%(asctime)s - %(levelname)s - %(message)s)formatleveliy)descriptionformatter_classr	   ?z;Maximum number of jobs to be kept pre-fetched in the queue.)nargstypehelpdefaultz
running %s zgensim.lsi_dispatcherr   zfinished running %s)!r[   rV   sysloggingargparser   rG   queuer   r   gensimr   	getLoggerrX   r    MAX_JOBS_QUEUErC   r   basicConfigINFOArgumentParserRawTextHelpFormatterparseradd_argumentint
parse_argsargsr!   joinargvpyro_daemonr	   progr0   r   r   <module>r~      s  0 0d 
			 



                     
	8	$	$ 
 "~ ~ ~ ~ ~ ~ ~ ~B z 4GJRYR^____$X$$QYQnoooF
J     D
KKchhsx00111E-zz$,/O/O/OPPP
KK%v{333334 4r   