@@ -14,9 +14,11 @@ You may obtain a copy of the License at
1414 limitations under the License.
1515******************************************************************************/
1616
17+ using Google . Protobuf ;
1718using System ;
1819using System . Diagnostics ;
1920using System . Linq ;
21+ using Tensorflow . Common . Extensions ;
2022
2123namespace Tensorflow . Contexts
2224{
@@ -25,12 +27,93 @@ namespace Tensorflow.Contexts
2527 /// </summary>
2628 public sealed partial class Context
2729 {
28- public ConfigProto Config { get ; set ; } = new ConfigProto
30+ protected Device . PhysicalDevice [ ] _physical_devices ;
31+ protected Dictionary < Device . PhysicalDevice , int > _physical_device_to_index ;
32+ ConfigProto _config ;
33+ public ConfigProto Config
2934 {
30- GpuOptions = new GPUOptions
35+ get
3136 {
37+ _initialize_physical_devices ( ) ;
38+
39+ var config = new ConfigProto ( ) ;
40+ if ( _config is not null )
41+ {
42+ config . MergeFrom ( _config ) ;
43+ }
44+ config . LogDevicePlacement = _log_device_placement ;
45+
46+ config . DeviceCount [ "CPU" ] = 0 ;
47+ config . DeviceCount [ "GPU" ] = 0 ;
48+ foreach ( var dev in _physical_devices )
49+ {
50+ if ( config . DeviceCount . ContainsKey ( dev . DeviceType ) )
51+ {
52+ config . DeviceCount [ dev . DeviceType ] += 1 ;
53+ }
54+ else
55+ {
56+ config . DeviceCount [ dev . DeviceType ] = 1 ;
57+ }
58+ }
59+
60+ var gpu_options = _compute_gpu_options ( ) ;
61+ config . GpuOptions = GPUOptions . Parser . ParseFrom ( gpu_options . ToByteArray ( ) ) ;
62+
63+ return config ;
64+ }
65+ set
66+ {
67+ _config = value ;
68+ }
69+ }
70+
71+ protected void _initialize_physical_devices ( bool reinitialize = false )
72+ {
73+ if ( ! reinitialize && _physical_devices is not null )
74+ {
75+ return ;
76+ }
77+ var devs = list_physical_devices ( ) ;
78+ _physical_devices = devs . Select ( d => new Device . PhysicalDevice ( )
79+ {
80+ DeviceName = d . DeviceName ,
81+ DeviceType = d . DeviceType
82+ } ) . ToArray ( ) ;
83+ _physical_device_to_index = _physical_devices . Select ( ( p , i ) => new KeyValuePair < Device . PhysicalDevice , int > ( p , i ) )
84+ . ToDictionary ( x => x . Key , x => x . Value ) ;
85+
86+ _import_config ( ) ;
87+ }
88+
89+ protected void _import_config ( )
90+ {
91+ if ( _config is null )
92+ {
93+ return ;
94+ }
95+ if ( ! _config . DeviceCount . TryGetValue ( "CPU" , out var num_cpus ) )
96+ {
97+ num_cpus = 1 ;
98+ }
99+ if ( num_cpus != 1 )
100+ {
101+ // TODO(Rinne): implement it.
32102 }
33- } ;
103+
104+ var gpus = _physical_devices . Where ( d => d . DeviceType == "GPU" ) ;
105+ if ( gpus . Count ( ) == 0 )
106+ {
107+ return ;
108+ }
109+
110+ if ( ! _config . DeviceCount . TryGetValue ( "GPU" , out var gpu_count ) )
111+ {
112+ gpu_count = 0 ;
113+ }
114+
115+ // TODO(Rinne): implement it.
116+ }
34117
35118 ConfigProto MergeConfig ( )
36119 {
0 commit comments