
    Q              	       f   S r SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSK	J
r
  SSKJr  SS	KJr  SS
KJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKJr  SSKrSrSrSrSrSr Sr!Sr"\RF                  " S\RH                  " 5       RJ                  RL                  SSRO                  \ \!5      4SSRO                  \"5      4S S!.S"S#S$9r(\RF                  " S%\RH                  " 5       RR                  RT                  S&S'S(.S)S#S$9r+S*S+S,S-S.S/S0.r,\RF                  " S1\RH                  " 5       RZ                  R\                  \,S2SS39r/ " S4 S5\05      r1S6 r2S7 r3S8 r4S9 r5S: r6S; r7S< r8S= r9S> r:S?r;SIS@ jr<SA r=SB r>                 SJSC jr?SD r@     SKSE jrASF rBSG rCSH rDg)Lzml-engine jobs command code.    )absolute_import)division)unicode_literals)
exceptions)jobs)stream)flags)	jobs_prep)	log_utils)	arg_utils)labels_util)execution_utils)log)
properties)	resources)yaml)resource_printerNzIhttps://console.cloud.google.com/mlengine/jobs/{job_id}?project={project}z[https://console.cloud.google.com/logs?resource=ml_job%2Fjob_id%2F{job_id}&project={project}zAyaml(jobId,state,startTime.date(tz=LOCAL),endTime.date(tz=LOCAL))
   z=https://www.tensorflow.org/guide/datasets#consuming_text_datazYhttps://cloud.google.com/ai-platform/prediction/docs/overview#batch_prediction_input_datazAhttps://www.tensorflow.org/guide/datasets#consuming_tfrecord_dataz--data-formattextzCText and JSON files; for text files, see {}, for JSON files, see {}z	tf-recordzTFRecord files; see {})ztf-record-gzipzGZIP-compressed TFRecord files.)TEXT	TF_RECORDTF_RECORD_GZIPzData format of the input files.T)custom_mappingshelp_strrequiredz--accelerator-type)znvidia-tesla-k80zNVIDIA Tesla K80 GPU)znvidia-tesla-p100zNVIDIA Tesla P100 GPU.)NVIDIA_TESLA_K80NVIDIA_TESLA_P100z$The available types of accelerators.)basiczSingle worker instance. This tier is suitable for learning how to use AI Platform, and for experimenting with new models using small datasets.)z
standard-1z)Many workers and a few parameter servers.)z	premium-1z4Large number of workers with many parameter servers.)z	basic-gpuz"Single worker instance with a GPU.)z	basic-tpuz(Single worker instance with a Cloud TPU.)customay  CUSTOM tier is not a set tier, but rather enables you to use your own
cluster specification. When you use this tier, set values to configure your
processing cluster according to these guidelines (using the `--config` flag):

* You _must_ set `TrainingInput.masterType` to specify the type of machine to
  use for your master node. This is the only required setting.
* You _may_ set `TrainingInput.workerCount` to specify the number of workers to
  use. If you specify one or more workers, you _must_ also set
  `TrainingInput.workerType` to specify the type of machine to use for your
  worker nodes.
* You _may_ set `TrainingInput.parameterServerCount` to specify the number of
  parameter servers to use. If you specify one or more parameter servers, you
  _must_ also set `TrainingInput.parameterServerType` to specify the type of
  machine to use for your parameter servers.  Note that all of your workers must
  use the same machine type, which can be different from your parameter server
  type and master type. Your parameter servers must likewise use the same
  machine type, which can be different from your worker type and master type.)BASIC
STANDARD_1	PREMIUM_1	BASIC_GPU	BASIC_TPUCUSTOMz--scale-tierzUSpecify the machine types, the number of replicas for workers, and parameter servers.)r   r   defaultc                   b    \ rS rSrSr                S	S jrS rS r\S
S j5       r	Sr
g)TrainingCustomInputServerConfigz   zCData class for passing custom server config for training job input.Nc                     X@l         X0l        XPl        X`l        Xpl        Xl        Xl        Xl        Xl        Xl	        Xl
        Xl        Xl        UU l        UU l        Xl        X l        UU l        g N)master_image_urimaster_machine_typemaster_accelerator_typemaster_accelerator_countparameter_machine_typeparameter_machine_countparameter_image_uriparameter_accelerator_typeparameter_accelerator_counttpu_tf_versionworker_machine_typeworker_machine_countworker_image_uriwork_accelerator_typework_accelerator_countruntime_version
scale_tieruse_chief_in_tf_config)selfr;   r<   r-   r,   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r=   s                      5lib/googlecloudsdk/command_lib/ml_engine/jobs_util.py__init__(TrainingCustomInputServerConfig.__init__}   su    & -2#: $<!"8#: 2&@#'B$(2 4,!6D"8D* O"8D    c                    U R                   (       a'  U R                  (       a  [        R                  " S5      eU R                  (       aA  U R                  R
                  S:X  a'  U R                  (       d  [        R                  " S5      eg)z9Validate that custom config parameters are set correctly.z=Only one of --master-image-uri, --runtime-version can be set.r%   zC--master-machine-type is required if scale-tier is set to `CUSTOM`.T)r,   r;   r	   ArgumentErrorr<   namer-   r>   s    r?   ValidateConfig.TrainingCustomInputServerConfig.ValidateConfig   sm    !5!5 !A B B4??//8;%%!! #C D 	DrB   c           
         U R                   U R                  U R                  S.S.U R                  U R                  U R
                  U R                  S.S.U R                  U R                  U R                  U R                  U R                  S.U R                  S.U R                  U R                  U R                  S.	$ )z=Return a mapping of object fields to apitools message fields.)counttype)imageUriacceleratorConfig)rL   rM   tpuTfVersion)	masterConfig
masterTypeparameterServerConfigparameterServerCountparameterServerTypeworkerConfigworkerCount
workerTypeuseChiefInTfConfig)r,   r/   r.   r-   r2   r4   r3   r1   r0   r8   r:   r9   r5   r7   r6   r=   rF   s    r?   GetFieldMap+TrainingCustomInputServerConfig.GetFieldMap   s     --6644"
 ..009977""
 !% < <#::--4422" !//
 00.."999 rB   c                 v   UR                   nU(       dS  UR                  (       aB  [        R                  " UR                  5      nUR	                  S0 5      R	                  SS5      n[        5       R                  U5      nU " S0 SU_SUR                  _SUR                  _SUR                  _SUR                  (       a  UR                  R	                  S	5      OS_S
UR                  (       a  UR                  R	                  S5      OS_SUR                  _SUR                  _SUR                  _SUR                  (       a  UR                  R	                  S	5      OS_SUR                  (       a  UR                  R	                  S5      OS_SU(       a  UR                  OS_SUR                   _SUR"                  _SUR$                  _SUR&                  (       a  UR&                  R	                  S	5      OS_SUR&                  (       a  UR&                  R	                  S5      OS_SUR(                  _6$ )z>Build TrainingCustomInputServerConfig from argparse.Namespace.trainingInput	scaleTierNr<   r;   r-   r,   r.   rK   r/   rJ   r0   r1   r2   r3   r4   r5   r6   r7   r8   r9   r:   r=    )r<   configr   	load_pathgetScaleTierFlagMapGetEnumForChoicer;   r-   r,   master_acceleratorparameter_server_machine_typeparameter_server_countparameter_server_image_uriparameter_server_acceleratorr5   r6   worker_countr8   worker_acceleratorr=   )clsargssupport_tpu_tf_versiontierdataparsed_tiers         r?   FromArgs(TrainingCustomInputServerConfig.FromArgs   s!    ??D	~~dkk*xx,00dC"$55d;K <<,,< !44< ..	< %)$;$; "&!8!8!<!<V!DAE< &*%<%< #'"9"9"="=g"FBF<  $AA< !% ; ;< !;;< ,, $(#D#D#H#H#P26< 99 %)$E$E$I$I%?C<  /Et**$!<" !44#<$ "..%<& ..'<* #'"9"9  $66::6B?C+<. $(#:#: !% 7 7 ; ;G D@D/<0  $::1< <rB   )r/   r.   r,   r-   r4   r3   r2   r1   r0   r;   r<   r5   r=   r:   r9   r8   r7   r6   )NNNNNNNNNNNNNNNN)F)__name__
__module____qualname____firstlineno____doc__r@   rG   rX   classmethodrp   __static_attributes__r]   rB   r?   r(   r(   z   s\    K
 $( $'+(,&*'+#'*.+/"#'$( $%)&*&*%$9L	B #< #<rB   r(   c                      [         $ )z7Return the ChoiceEnumMapper for the --data-format flag.)_PREDICTION_DATA_FORMAT_MAPPERr]   rB   r?   DataFormatFlagMapr{      s    	''rB   c                      [         $ )z<Return the ChoiceEnumMapper for the --accelerator-type flag.)_ACCELERATOR_MAPr]   rB   r?   AcceleratorFlagMapr~      s    	rB   c                      [         $ )z7Returns the ChoiceEnumMapper for the --scale-tier flag.)_TRAINING_SCALE_TIER_MAPPERr]   rB   r?   ra   ra      s    	$$rB   c                     [         R                  R                  U S[        R                  R
                  R                  R                  0SS9$ )N
projectsIdml.projects.jobsparams
collection)r   REGISTRYParser   VALUEScoreproject	GetOrFailjobs    r?   	_ParseJobr     sF    				!	!	J--22::DDE# 
" 
% %rB   c                 :    [        U5      nU R                  U5      $ r+   )r   Canceljobs_clientr   job_refs      r?   r   r     s    cN'			G	$$rB   c                 4   [         R                  R                  R                  R	                  5       n[
        R                  R                  S[        R                  XS9-   5        [
        R                  R                  S[        R                  XS9-   5        g )Nz#
View job in the Cloud Console at:
job_idr   z
View logs at:
)r   r   r   r   Getr   statusPrint_CONSOLE_URLformat	_LOGS_URLr   s     r?   PrintDescribeFollowUpr     sz    ""**..0'**-9:; **f678rB   c                 :    [        U5      nU R                  U5      $ r+   )r   r   r   s      r?   Describer     s    cN'		!!rB   c                     [         R                  R                  [        R                  R
                  R                  R                  SS9SS9nU R                  U5      $ )NTr   ml.projectsr   )	r   r   r   r   r   r   r   r   List)r   project_refs     r?   r   r      sV    ""(($$(($(7 )  + 
		+	&&rB   c                     [         R                  " [        R                  " X5      U[        [        R
                  " U 5      S9n[        R                  " UR                  5       US9$ )Nfilterspolling_intervalcontinue_intervalcontinue_func)allow_multiline)r   
LogFetcherr   
LogFilters_CONTINUE_INTERVALMakeContinueFunctionSplitMultiline	YieldLogs)r   	task_namer   allow_multiline_logslog_fetchers        r?   
StreamLogsr   '  sZ    !!""32';M22379+ 
	!	!/C
E ErB   zYour job is still active. You may view the status of your job with the command

  $ gcloud ai-platform jobs describe {job_id}

or continue streaming the logs with the command

  $ gcloud ai-platform jobs stream-logs {job_id}c                     [         R                  R                  SR                  U 5      5        U(       a1  [         R                  R                  [        R                  U S95        g g )Nz Job [{}] submitted successfully.)r   )r   r   r   r   _FOLLOW_UP_MESSAGE)r   print_follow_up_messages     r?   PrintSubmitFollowUpr   <  sI    **5<<VDEJJ'..f.=> rB   c                 r    U (       a  U(       a  [        S5      eU (       a  [        R                  " S5        U$ )a  Return, based on the command line arguments, whether we should stream logs.

Both arguments cannot be set (they're mutually exclusive flags) and the
default is False.

Args:
  asyncronous: bool, the value of the --async flag.
  stream_logs: bool, the value of the --stream-logs flag.

Returns:
  bool, whether to stream the logs

Raises:
  ValueError: if both asyncronous and stream_logs are True.
z---async and --stream-logs cannot both be set.zThe --async flag is deprecated, as the default behavior is to submit the job asynchronously; it can be omitted. For synchronous behavior, please pass --stream-logs.
)
ValueErrorr   warning)asyncronousstream_logss     r?   GetStreamLogsr   B  s5      [ D
EEKK I J 
rB   c                 V    [         R                  " XR                  R                  5      $ r+   )r   ParseCreateArgs	job_classLabelsValue)r   rk   s     r?   ParseCreateLabelsr   ^  s    		$	$T+@+@+L+L	MMrB   c                 	   [         R                  R                  R                  R	                  SS9n[
        R                  " X1US9n [
        R                  " UUUS9n[        R                  " SR                  U5      5        U R                  R                  nU(       a  U" U5      OSn U R!                  UUUUUU(       a  UR#                  5       OSUUU	U
UUUUUUS9n[$        R&                  R)                  [         R                  R*                  R,                  R	                  SS9S
S9nU R/                  UU5      nU(       d  [1        UR2                  SS9  U$ [1        UR2                  SS9  [4        R6                  " [8        R:                  " UR2                  5      [         R                  R<                  R>                  RA                  5       [B        [8        RD                  " UR2                  5      S9n[F        RH                  " [8        RJ                  [        RL                  S9n[N        RP                  " 5           URS                  [8        RT                  " URW                  5       5      5        SSS5        [$        R&                  R)                  UR2                  S[         R                  R*                  R,                  Rj                  0SS9nU R	                  U5      nU$ ! [
        R                   a    [        R                  " S5      ef = f! [
        R                   a    [        R                  " S	5      ef = f! [X         al    [        RZ                  RS                  S5        [        RZ                  RS                  [\        R                  UR2                  UR_                  5       S95         GNC[`        Rb                   a  n[        RZ                  RS                  SR                  [d        Rf                  " U5      5      5        [        Rh                  " SSS9  [        RZ                  RS                  [\        R                  UR2                  UR_                  5       S95         SnAGNSnAff = f! , (       d  f       GN= f)zSubmit a training job.Tr   )staging_bucketr   job_dir)packagespackage_pathstaging_locationzYIf local packages are provided, the `--staging-bucket` or `--job-dir` flag must be given.zUsing {0} as trainer urisN)pathmodule_namejob_nametrainer_uriregionr   r<   	user_argsr;   networkservice_accountpython_versionlabelskms_keycustom_train_server_configenable_web_accesszeIf `--package-path` is not specified, at least one Python package must be specified via `--packages`.r   r   r   Fr   )outzReceived keyboard interrupt.
r   zPolling logs failed:
{}
zFailure details:)exc_infor   r   r   )6r   r   computer   r   r
   GetStagingLocationUploadPythonPackagesNoStagingLocationErrorr	   rD   r   debugr   training_input_classScaleTierValueValuesEnumBuildTrainingJobToUrlr   r   r   r   r   Creater   jobIdr   r   r   r   	ml_enginer   GetIntr   r   r   Printer
LOG_FORMATerrr   RaisesKeyboardInterruptr   r   r   KeyboardInterruptr   r   Namer   	HttpErrorsix	text_typeinfor   )r   r   r   r   r   r   r<   r^   r   r;   r   r   r   r   r   r   r   r   r   r   r   urisscale_tier_enumr   r   printerr   r   s                               r?   SubmitTrainingr   b  s   ( $$++///>&11#+))!)+D ))'..t4544MM/.8z*d*/

&
&#*''%#=+! ' -C, ""(($$(($(7 )  + 	;,#			4@J		5A!!""399-!((22CCJJL*22399=	?+ $$Y%9%9),2'..0
NmmI,,[-B-B-DEF 1 $$	iiJ--22::DDE# % %' 	 #	*K 
	)	) +


	*+ ++6 
	)	) /


	./ //4  N	jj78	jj)00		9D9I9I9K 1 M N N	jj3::3==;MNO	hh!D1	jj)00		9D9I9I9K 1 M N NN 10sV   K$ +5L =Q6?3M $+L+L= A2Q32Q65Q3B Q.(Q6.Q33Q66
Rc                 N    U (       a  U(       a  [         R                  " S5      eg g )Nz,`--version` cannot be set with `--model-dir`)r	   rD   )	model_dirversions     r?   _ValidateSubmitPredictionArgsr     s     7


L
MM YrB   c                 ^   [        X$5        [        R                  R                  [        R
                  R                  R                  R                  SS9SS9nU R                  UUUUUUUUU	U
UUUU[        R                  U5      S9n[        UR                  SS9  U R                  UU5      $ )zSubmit a prediction job.Tr   r   r   )r   r   
model_nameversion_nameinput_pathsdata_formatoutput_pathr   r;   max_worker_count
batch_sizesignature_namer   accelerator_countaccelerator_typer   )r   r   r   r   r   r   r   r   r   BuildBatchPredictionJobr}   rb   r   r   r   )r   r   r   modelr   r   r   r  r   r;   r  r  r  r   r  r  r   s                    r?   SubmitPredictionr	    s      	3""(($$(($(7 )  + 	++%'#)'889IJ 	, 	#" cii>			K	--rB   c                     U (       am  [        U SS5      (       aF  [        U R                  SS5      (       a  [        R                  " 5       $ [        R                  " 5       $ [        R
                  " 5       $ g)zGet summary table format for an ml job resource.

Args:
  job: job resource to build summary output for.

Returns:
  dynamic format string for resource output.
r[   Fhyperparametersr   )getattrr[   r	   GetHPTrainingJobSummaryGetStandardTrainingJobSummaryGetPredictJobSummaryr   s    r?   GetSummaryFormatr    s\     	sOU++	""$5u	=	=,,..0022''))	rB   c                 l   ^ ^ U U4S jn[         R                  " UT R                  R                  U5      $ )Nc                  :   > T R                  T5      R                  $ r+   )r   r   )clientr   s   r?   	GetLabels$ParseUpdateLabels.<locals>.GetLabels  s    ::g%%%rB   )r   ProcessUpdateArgsLazyr   r   )r  r   rk   r  s   ``  r?   ParseUpdateLabelsr     s.    &		*	*
F(()
5 5rB   c                   ^ [        TR                  5      n[        XT5      n U R                  X#5      $ ! [        R
                   a=    [        U4S jS 5       5      (       d  e [        R                  R                  S5         gf = f)zUpdate a job.c              3   F   >#    U  H  nTR                  U5      v   M     g 7fr+   )IsSpecified).0argrk   s     r?   	<genexpr>Update.<locals>.<genexpr>  s*      C 1Bt$$ 1Bs   !)update_labelsclear_labelsremove_labelszNo update to perform.N)
r   r   r  Patchr   NoFieldsSpecifiedErroranyr   r   r   )r   rk   r   labels_updates    `  r?   Updater&    s    dhh'#K$?-W44		$	$  C 1B C C C JJ,-s   5 ABB)T)NNNNNNNNNNNNNNNNN)NNNNNNNNNNNNNN)Erv   
__future__r   r   r   apitools.base.pyr    googlecloudsdk.api_lib.ml_enginer   googlecloudsdk.command_lib.logsr   $googlecloudsdk.command_lib.ml_enginer	   r
   r   $googlecloudsdk.command_lib.util.apisr   $googlecloudsdk.command_lib.util.argsr   googlecloudsdk.corer   r   r   r   r   googlecloudsdk.core.resourcer   r   r   r   
JOB_FORMATr   _TEXT_FILE_URL_JSON_FILE_URL_TF_RECORD_URLChoiceEnumMapperGetMessagesModuleGoogleCloudMlV1PredictionInputDataFormatValueValuesEnumr   rz    GoogleCloudMlV1AcceleratorConfigTypeValueValuesEnumr}   _SCALE_TIER_CHOICESGoogleCloudMlV1TrainingInputr   r   objectr(   r{   r~   ra   r   r   r   r   r   r   r   r   r   r   r   r   r	  r  r  r&  r]   rB   r?   <module>r=     sD   # &  ' ' 1 2 6 : : : < / # * ) $ 9 
$E	P
  )9- "+!;!; $$%>%>"F>>BE ".55nEG> /"   -- &&':':HL 4	 P NJDJ < (88!!":":'' y<f y<x(

%
%%
8"
'E ?8N  "&  $"##'#'"&#!.2%)%bJN :>EIIMBF>B.B&5rB   